基本幻灯片程序

Basic slideshow program

这只是使用 js 的基本幻灯片放映,但我没有得到输出。我想让它执行自动幻灯片放映,我应该在我的程序中添加 jquery 脚本吗?请帮帮我

<script>
var images = new Array(); 
images[0] = new Image(); 
images[0].src = "first.jpg"; 
images[1] = new Image();
images[1].src = "second.jpg";
images[2] = new Image();
images[2].src = "third.jpg";

</script>
</head>
<body>
<img src="first.jpg" id="slide" width="500" height="500" />

<script type="text/javascript">


var step=0;

function slideit(){

 document.getElementById('slide').src = images[step].src;
 if (step<2)
  step++;
 else
  step=0;

 setTimeout("slideit()",2500);
}

slideit();

</body>

您需要使用 setInterval() 而不是 setTimeout(),您的代码也可以简化为以下内容。

var images = ['http://dummyimage.com/300x100/025870/fff', 'http://dummyimage.com/300x100/456e02/fff', 'http://dummyimage.com/300x100/6e2b02/fff'];
var step = 0;

setInterval(function() {
  document.getElementById('slide').src = images[step++ % images.length];
}, 2500);
<img src="http://dummyimage.com/300x100/025870/fff" id="slide" width="300" height="100" />

注意模数的使用(%)。为了更好地理解它,这里是正在发生的事情:

1st iteration: (step++ % images.length) ⇒ (0 % 3) ⇒ 0,  
2nd iteration: (step++ % images.length) ⇒ (1 % 3) ⇒ 1,   
3rd iteration: (step++ % images.length) ⇒ (2 % 3) ⇒ 2,   
4th iteration: (step++ % images.length) ⇒ (3 % 3) ⇒ 0,   
5th iteration: (step++ % images.length) ⇒ (4 % 3) ⇒ 1 and so on...

每次step的值被图像数量整除,如果回滚到0