如何自动循环一系列图像?

时间:2016-03-04 12:13:21

标签: javascript html arrays

我需要让一组图像自动更改,它们的交通灯是精确的。我正在使用一个带有按钮的数组,使其发生变化,但我需要自动循环。我该怎么做呢?

<img id="light" src="N:\Computing Year 10\Year 10 CS\A452 - First Assessment\Programming\trafficlights\1red.png">

<button type="button" onclick="changeLights()">Change Lights</button> <!-- Button used to change lights-->
var lightList = [
    "1red.png",       /* index 0 */
    "2redamber.png",  /* index 1 */
    "3green.png",     /* index 2 */
    "4amber.png"      /* index 3 */
];

var index = 0;  /* New variable called 'index' set to 0 */

function changeLights() {
    index = index + 1;     /* This assigns the changeLights buttom the function of addind 1 to the value of index, which changes the traffic light */

    if (index == lightList.length) index = 0;

    var image = document.getElementById('light');
    image.src=lightList[index];
}

http://pastebin.com/Bwk7E61Y

1 个答案:

答案 0 :(得分:1)

您可以使用changeLights()每秒调用setInterval功能。您可以阅读setInterval函数here。您可以选择调用该函数的时间间隔。

window.onload = function() {
    setInterval(function(){ 

    changeLights();

    }, 1000);
}