我想通过用户输入(按钮)运行此代码,但我不知道如何操作。另外,我从互联网上得到了一些代码,所以我仍然不太明白为什么颜色变量的数组中有 6 种颜色,而不是只有 3 种(红、黄、绿)。我对 if 语句的理解也不足以写出它,所以如果你能解释为什么我实际上需要 var 时间,那就太好了。谢谢!
var time = 5;
function lights() {
var red = document.getElementById('redLight')
var yellow = document.getElementById('yellowLight')
var green = document.getElementById('greenLight')
var Colours = ["#FF0000", "#FFB300", "#05FF0D", "#7A0000", "#7A5C00", "#008000"];
if (time == 5) {
red.style.background = Colours[0];
yellow.style.background = Colours[4];
green.style.background = Colours[5];
time = 1;
} else if (time == 2 || time == 4) {
red.style.background = Colours[3];
yellow.style.background = Colours[1];
green.style.background = Colours[5];
} else if (time == 3) {
red.style.background = Colours[3];
yellow.style.background = Colours[4]
green.style.background = Colours[2];
}
time += 1
};
setInterval(function() {
lights();
}, 2000);
<h1> Traffic Light </h1>
<div id="redLight"></div>
<div id="yellowLight"></div>
<div id="greenLight"></div>
<div id="box"></div>
最佳答案
您可以使用 <button onclick="test()"></button>
添加按钮
然后你将间隔放入我称为 test 的函数中。喜欢:
function test(){setInterval(lights(),2000)
关于javascript - 如何向此 JavaScript 和 HTML 代码添加一个按钮,以便当我按下该按钮时,我的交通灯序列运行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42752526/