我想控制此幻灯片开始/停止在#mainImage上使用onclick。此时,我可以停止播放幻灯片,但我仍然坚持使用onclick再次启动它的逻辑。理想情况下,我希望幻灯片放映从它停止的阵列位置继续,而不是完全重新开始。我的直觉告诉我这可以通过一些条件陈述来解决,但我无法让它发挥作用。感谢您的任何反馈!
//Grab img
var mainImage = document.getElementById("mainImage");
//Create image array
var imageArray = ["images/drifter.jpg","images/drifter3.jpg","images/drifter4.jpg"];
//Set up array index
var imageIndex = 0;
//Create function to cycle through images
function changeImage() {
mainImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
//Call cycle function
var intervalHandle = setInterval(changeImage,3000);
mainImage.onclick = function () {
clearInterval(intervalHandle);
}
答案 0 :(得分:0)
添加一个标志以了解它何时停止以及何时应该继续
//Grab img
var mainImage = document.getElementById("mainImage");
//Create image array
var imageArray = ["images/drifter.jpg","images/drifter3.jpg","images/drifter4.jpg"];
//Set up array index
var imageIndex = 0;
// here the flag
var stop = false;
//Create function to cycle through images
function changeImage() {
mainImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
//Call cycle function
var intervalHandle = setInterval(changeImage,3000);
mainImage.onclick = function () {
if(!stop){
clearInterval(intervalHandle);
stop = true;
} else {
intervalHandle = setInterval(changeImage,3000);
stop = false;
}
}