gpt4 book ai didi

Javascript改变图片

转载 作者:行者123 更新时间:2023-11-30 00:07:45 25 4
gpt4 key购买 nike

所以我用了两张图片和setInterval随着时间连续改变两张图片。当我点击图片时,我会使用 clearInterval 来卡住图像。我的问题是当我点击它时如何让两个图像再次连续变化?所以这就像一个断断续续的场景。下面是使两张图片连续变化的代码,当我点击它时,图像卡住并且它们之间不发生变化。

var imageArray = ["_images/korea.jpg","_images/images.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length){
imageIndex = 0;
}
}
var test = setInterval(changeImage, 1000);
myImage.onclick = function(){
clearInterval(test);
}

最佳答案

代替 clearInterval,使用 Boolean flag 并在点击 image< 时反转

var imageArray = ["_images/korea.jpg", "_images/images.jpg"];
var imageIndex = 0;
var flag = true;

function changeImage() {
if (flag) {
myImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
}
setInterval(changeImage, 1000);
myImage.onclick = function() {
flag = !flag;
}

或者您可以重新启动setInterval

var imageArray = ["_images/korea.jpg", "_images/images.jpg"];
var imageIndex = 0;
var interval;
var clicked = false;

function changeImage() {
myImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
interval = setInterval(changeImage, 1000);
myImage.onclick = function() {
if (!clicked) {
clearInterval(interval);
clicked = true;
} else {
interval = setInterval(changeImage, 1000);
clicked = false;
}

}

关于Javascript改变图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37851320/

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