【发布时间】:2017-06-18 13:32:07
【问题描述】:
light 和 order 都是包含状态及其显示时间段的数组。
但是,我不太确定 Index 的作用或“sId”。有人可以解释一下吗?该代码更改了交通信号灯的顺序。该代码有效,但我想知道lightIndex 做了什么,因为当我更改它时它不起作用。
<!DOCTYPE html>
<html>
<style type="text/css">
.light {
height: 30px;
width: 30px;
border-style: solid;
border-width: 2px;
border-radius: 25px;
}
.lightRed {
background-color: red;
}
.lightYellow {
background-color: yellow;
}
.lightGreen {
background-color: green;
}
</style>
<body>
<div id="trafficLight">
<div>Click to Start and Stop</div>
<div class="light" id="Red"></div>
<div class="light" id="Yellow"></div>
<div class="light" id="Green"></div>
</div>
<button type="button" onclick="changeState()">Change Lights</button>
<button type="button" onclick="changeState()">automatic</button>
<script>
var changeState = (function () {
var state = 0,
lights = ["Red", "Yellow", "Green"],
lightsLength = lights.length,
order = [
[7000, "Red"],
[2000, "Red", "Yellow"],
[7000, "Green"],
[2000, "Yellow"]
],
orderLength = order.length,
lightIndex,
orderIndex,
sId;
return function (stop) {
if (stop) {
clearTimeout(sId);
return;
}
var light,
lampDOM;
for (lightIndex = 0; lightIndex < lightsLength; lightIndex += 1) {
light = lights[lightIndex];
lightDOM = document.getElementById(light);
if (order[state].indexOf(light) !== -1) {
lightDOM.classList.add("light" + light);
} else {
lightDOM.classList.remove("light" + light);
}
}
sId = setTimeout(changeState, order[state][0]);
state += 1;
if (state >= orderLength) {
state = 0;
}
};
}());
document.querySelector('change Lights', 'automatic').addEventListener("click", (function () {
var state = false;
return function () {
changeState(state);
state = !state;
};
}()), false);
</script>
</body>
</html>
【问题讨论】:
标签: javascript html css indexing integer