我正在尝试创建一个简单的幻灯片..某些东西不太正确,我不确定是什么。由于某种原因,正在调用startSlideShow函数,但没有实现“位置”变量的更改......
HttpWebRequest
var timer = null;
var position = 0;
var images = document.querySelectorAll('.slide img');
for (let i = 0; i < images.length; i++) {
images[i].src = 'dog' + i + '.jpg';
var button = document.getElementById('control');
button.onclick = run;
function run() {
if (timer == null) { //stopped or page has just loaded
timer = setInterval(startSlideShow, 4000);
} else {
clearInterval(timer); //this stops animation
timer = null;
}
};
function startSlideShow() {
position++;
images[i].style.left = position + 'px';
};
}
答案 0 :(得分:0)
您所遵循的逻辑是相反的。图像循环应该从按下按钮开始,其中需要附加点击事件监听器。因此迭代的函数需要包含循环。 尝试使用带有箭头功能的IE6语法的代码。如果您需要IE5,请告诉我,但我想如果您需要,您可以轻松找出如何进行转换。
我刚刚重构了解决方案,以便像幻灯片一样:)
这是工作JsFiddle:https://jsfiddle.net/0t00oax8/
请尝试以下代码
var timer = null;
var position = 0;
var images = document.querySelectorAll('.slide img');
const showNextPic = () => {
images[ (position > 0) ? (position-1) : 0 ].style = "display:none";
if( position >= images.length){
position = 0;
}
let imgName = 'dog' + position + '.jpg'
images[position].src = imgName;
images[position].alt = imgName;
images[position].style = "display:block"
position++;
}
var button = document.getElementById('control');
button.addEventListener('click', () => {
if (timer == null) { //stopped or page has just loaded
timer = setInterval(showNextPic, 2000);
}else {
clearInterval(timer); //this stops animation
timer = null;
}
}) ;
希望这有帮助!