基本幻灯片程序

时间:2015-01-24 12:35:16

标签: javascript jquery html css image

这只是一个使用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>

1 个答案:

答案 0 :(得分:2)

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

&#13;
&#13;
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);
&#13;
<img src="http://dummyimage.com/300x100/025870/fff" id="slide" width="300" height="100" />
&#13;
&#13;
&#13;

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

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

相关问题