我被要求创建一个红绿灯,它使用数组通过序列集。
我已经成功地创建了一个红绿灯,每当用户想要改变红绿灯的颜色时,它都可以与用户按下按钮一起工作。然而,我现在的任务是制作它,这样用户只需按一次按钮,然后它就会使用JavaScript自动完成序列。
代码中使用的图像与脚本位于同一文件夹中。
<img id="Change Lights" src="red.gif" width="36" height="98">
<br>
<button onclick="nxt()" id="button">Change colour</button>
</br>
<script>
var img = new Array("red.png", "amberred.png", "green.png", "amber.png");
var imgElement = document.getElementById("Change Lights");
var lights = 0;
var imgLen = img.length;
function nxt() {
if (lights < imgLen - 1) {
lights++;
} else {
lights = 0;
}
imgElement.src = img[lights];
}
</script>
发布于 2016-12-10 02:50:57
<img id="Change Lights" src="https://placehold.it/36x98/ff0000" width="36" height="98">
<script>
var img = ["https://placehold.it/36x98/ffbf00","https://placehold.it/36x98/00ff00","https://placehold.it/36x98/ff0000"];
var imgElement = document.getElementById("Change Lights");
var lights = 0;
var imgLen = img.length;
function nxt() {
if (lights < imgLen - 1) {
lights++;
} else {
lights = 0;
}
imgElement.src = img[lights];
}
setInterval(nxt,2000);
</script>
https://stackoverflow.com/questions/41066911
复制相似问题