0

如何在 JavaScript 中重置间隔 onclick。我有以下教程,一切正常,我可以让杂耍在点击时重新开始。

var myImage = document.getElementById("mainImage");

var imageArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg",
             _images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"];
                 var imageIndex = 0;


function changeImage (){
    myImage.setAttribute("src",imageArray [imageIndex]);
    imageIndex++;

if (imageIndex >= imageArray.length){
    imageIndex = 0;
}
 }

 var intervalHandler = setInterval(changeImage, 5000);
myImage.onclick = function (){
    clearInterval(intervalHandler);
}

**// The code below doesn’t work**

 var intervalReset = clearInterval;
myImage.onclick = function (){
    setInterval(intervalReset);
};
4

2 回答 2

0

您设置onclick了两次,它替换了处理程序,因此只有后面的定义才会计算在内。改用addEventListener

myImage.addEventListener("click", function() {
    //first set of stuff
});

myImage.addEventListener("click", function() {
    //more stuff
});

只有你的第一个功能才有意义。您可能还想重置imageIndex为 0。

总而言之,您的代码应如下所示:

var intervalHandler = setInterval(changeImage, 5000);
myImage.addEventListener("click", function() {
    clearInterval(intervalHandler);
    imageIndex = 0;
    intervalHandler = setInterval(changeImage, 5000); //restart again
});
于 2013-01-09T11:19:02.873 回答
0

setInterval 返回一个用于清除间隔的间隔 ID:

var intervalDuration = 5000;
myImage.onclick = function (){
    clearInterval(intervalHandler);
    // Assumes intervalDuration is defined
    intervalHandler = setInterval(changeImage, intervalDuration);
};
于 2013-01-09T11:21:04.277 回答