java脚本中的自动交通灯序列

时间:2016-10-11 11:02:37

标签: javascript html

我写了下面的代码,它在三个图像之间发生变化,红色的琥珀色和绿色的交通信号灯,每次我点击它在灯光之间切换的按钮。我想知道的是,如果有一种方法我可以点击按钮一次,序列将由它自己运行。红色至琥珀色至绿色暂停,然后再次变为琥珀色然后再次变为红色,每次单击该按钮时都会发生这种情况。是可以做的,我怎么可以这样问我可以尝试编码呢?

<!DOCTYPE html>
<html>
<Head>
<script>
var trafficlights=['redlight.png','yellowlight.png','greenlight.png','yellowlight.png'];
var num=1


function lightsequence(){
    document.getElementById('light').src = trafficlights[num++ % trafficlights.length];
}
</script>
</Head>
<body>
<img id="light" src="redlight.png">
<button onclick="lightsequence()">Change Lights</button>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

尝试:

    var num = 0;
    var timeoutId = 0;    
    function lightsequence(){
        if (num >= trafficlights.length) {
                num = 0;
        }

        document.getElementById('light').src = trafficlights[num];
        num += 1;
    }

    function startTL() {
        lightsequence(); // Run once first.
        timeoutId = setInterval(lightsequence, 1000); // Run every second
    }

答案 1 :(得分:0)

将此添加到函数lightsequence

if (num % trafficlights.length != 1)
    window.setTimeout(lightsequence, 500);

我在下面应用它,使用带背景颜色的div而不是图像:

var red = '#cc0605';
var yellow = '#fad201';
var green = '#27e833';
var colors = [red, yellow, green, yellow];

var num=1;
function divLight() {
    return document.getElementById('light');
}

function lightsequence(){
    divLight().style.background = colors[num++ % colors.length];
    if (num % colors.length != 1)
        window.setTimeout(lightsequence, 500);
}
<!DOCTYPE html>
<html>
<body onload="divLight().style.background = red;">
    <div id="light" style="width:20px;height:20px"></div>
    <button onclick="lightsequence()">Change Lights</button>
</body>
</html>