[英]Array image looping in JavaScript
I have been trying to loop traffic light images in JavaScript. 我一直试图在JavaScript中循环交通灯图像。 I'm not sure what to do, can someone give advice.
我不确定该怎么办,有人可以提供建议吗?
A slight modification to your code. 对您的代码稍作修改。 Here is a working sample.
这是一个工作示例。
I removed the dvi.count
counter as it creates more confusion, We need to maintain the counters outside the function. 我删除了
dvi.count
计数器,因为它造成了更多混乱,我们需要在功能之外维护计数器。 I changed the logic to pass around the index of the image in the array starting from 0. 我更改了逻辑以从0开始传递数组中图像的索引。
var image = new Array("red.jpg", "redamber.jpg", "green.jpg", "amber.jpg"); var timeout; function stopIt() { clearTimeout(timeout); } function changeimage (images, index) { var dvi = document.getElementById(images); if(image.length <= index) index = 0; dvi.src = image[index]; dvi.alt = image[index]; timeout = setTimeout('changeimage("' + images + '",' + (index + 1) + ')', 1000); }
<body onload="changeimage('changer',0)"> <div> <img src="t1" alt="test1" id="changer" /> </div> </body>
I have made 3 changes to your code 我对您的代码进行了3次更改
div.count
to dvi.count
div.count
为dvi.count
if
statement (Not strictly necessary, but makes the code way more readable) if
语句周围加了花括号(并非绝对必要,但使代码更具可读性) setTimeout
to be a function reference setTimeout
中的字符串参数用作函数引用 function changeimage(images){
var dvi=document.getElementById(images);
if(!dvi.count || dvi.count == image.length ){
dvi.count=0;
}
dvi.src=image[dvi.count];
dvi.alt=image[dvi.count];
dvi.count=dvi.count+1;
timeout=setTimeout(function(){
changeimage(images);
},3500);
}
Live example: https://jsfiddle.net/Lofug2hf/1/ 实时示例: https : //jsfiddle.net/Lofug2hf/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.