如果可能的话,我们希望在单击时将此图像更改为另一个图像,并总共重复此过程六次,因此每次单击它都会-6ren">
gpt4 book ai didi

javascript - 点击后将图像更改为另一个图像

转载 作者:行者123 更新时间:2023-12-03 10:12:43 25 4
gpt4 key购买 nike

我们目前正在支架(ch-item)内创建图像,如下所示:

<div class="ch-item ch-img-1" style="background: url(<?php echo get_template_directory_uri(); ?>/images/image1.jpg);">

如果可能的话,我们希望在单击时将此图像更改为另一个图像,并总共重复此过程六次,因此每次单击它都会更改为另一个图像。

我们将不胜感激任何帮助。谢谢!

最佳答案

这是仅使用 Javascript 实现此目的的一种方法:

// Counter to keep track of which the current image is
var counter = 0;

// List of images
var images = [
'http://cdn.cutestpaw.com/wp-content/uploads/2011/11/Seemly-l.jpg',
'http://cdn.cutestpaw.com/wp-content/uploads/2011/11/Handsome-l.jpg',
// Add more images here
];

window.onload = function () {
// Get the container div
var gallery = document.getElementById('gallery');

// Run updateImage function on click
gallery.addEventListener('click', updateImage);

// Run updateImage on start
updateImage();
}

function updateImage() {
// Get the container div
var gallery = document.getElementById('gallery');

// Set background image
gallery.style.backgroundImage = 'url(' + images[counter] + ')';

// Update counter
counter++;

// Remove old class name
if (counter == 1) { // Remove last
gallery.className = gallery.className.replace(
' ch-img-' + images.length,
''
);
} else { // Remove previous
gallery.className = gallery.className.replace(
' ch-img-' + (counter - 1),
''
);
}

// Add new class name
gallery.className = gallery.className + ' ch-img-' + (counter);

// Reset counter when at the end of the images list
if (counter == images.length) {
counter = 0;
}
}

这里有一个 JSFiddle 可供尝试:

https://jsfiddle.net/0tg6up0o/14/

关于javascript - 点击后将图像更改为另一个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30035619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com