[英]JavaScript Slideshow with 4 images
我正在尝试创建一个简单的幻灯片..不太正确,我不确定是什么。 由于某种原因,正在调用startSlideShow函数,但未实现对“ position”变量的更改...
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'; }; }
<div class="slideshow"> <div class="slide-container"> <div class="slide"> <img> </div> <div class="slide"> <img> </div> <div class="slide"> <img> </div> <div class="slide"> <img> </div> </div> </div> <button id="control">Stop/Start</button>
您遵循的逻辑是相反的。 图像循环应从按下按钮开始,其中需要附加单击事件监听器。 因此,迭代的功能需要封闭循环。 请尝试以下代码,该代码使用带有箭头功能的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;
}
}) ;
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.