简体   繁体   English

使用计时器循环遍历HTML中的图像

[英]Loop through images in HTML with a timer

This is my code, it only outputs the original red image and i don't understand how i'm supposed to make the code able to loop. 这是我的代码,它只输出原始的红色图像,我不明白如何使代码能够循环。 Could someone help as I need this code desperately? 我迫切需要此代码时有人可以提供帮助吗?

<!DOCTYPE html>
<html>
<head>
<h1> The traffic script</h1>
<script>


var list = [
    "H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/red.jpg",
    "H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/amber.jpg",
    "H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/green.jpg"
];

var index = 0;

function changeLights() {
    index = index + 1;
    if (index == list.length) index = 0;
    var image = document.getElementById('red');
    image.src=list[index];
}
window.onload = changelights;
</script>
</head>

<body>
<img id="red" src="H:/GCSE COMPUTING/a452/traffic     thingy/traffic/bleh/red.jpg">
</body>
</html> 

Use SetInterval - this is not a loop like a for loop, etc. It is simply a block of code that will get triggered every x miliseconds. 使用SetInterval-这不是像for循环这样的循环。它只是一个代码块,每隔x毫秒就会触发一次。

var list = [
    "H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/red.jpg",
    "H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/amber.jpg",
    "H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/green.jpg"
];


   var index = 0;

function changeLights() {
    index = index + 1;
    if (index == list.length) index = 0;
    var image = document.getElementById('red');
    image.src=list[index];
}
setInterval(function(){changeLights()}, 4000);

This will call changeLights every 4 seconds. 这将每4秒调用一次changeLights。 Also - be careful asking GCSE questions here especially the course work. 另外-请谨慎询问此处的GCSE问题,尤其是课程作业。

JavaScript has a built-in interval method, which can be used as a loop in this case. JavaScript具有内置的interval方法,在这种情况下可以用作循环。

var backgroundInterval = setInterval(function() {
    changeLights();

    if(index == (list.length - 1)) {
        clearInterval(backgroundInterval); // stop the loop when it hits last image
    }
}, 4000); // every 4000 ms, or 4s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM