我的Javascript / Html流量灯序列需要一个循环

时间:2016-12-31 15:17:12

标签: javascript html

我需要确保单击按钮时图像会发生变化,但是当我测试代码时图像会发生变化但是在一个周期后它们会停止。请给出一些关于如何添加循环或重复代码的可能解决方案,谢谢。



var red = "data:image/gif;base64,R0lGODlhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=",
    redorange = "data:image/gif;base64,R0lGODlhAQABAIABAP9aAAAAACwAAAAAAQABAAACAkQBADs=",
    green = "data:image/gif;base64,R0lGODlhAQABAIABAAD/AAAAACwAAAAAAQABAAACAkQBADs=",
    orange = "data:image/gif;base64,R0lGODlhAQABAIABAP+qAAAAACwAAAAAAQABAAACAkQBADs=";

var lights = [red, redorange, green, orange];
var lightCounter = 0;

function pictureChange(){
  lightCounter += 1;
  document.getElementById('traffic').src = lights[lightCounter];
}

h1 {
  text-align: center;
}

img {
  display: block;
  margin: 0 auto;
}

<h1><b> Traffic Lights </b></h1>

<center>
  <button onclick="pictureChange()">Change Lights</button>
</center>

<br><br>

<img width="230" height="400" id="traffic" src="data:image/gif;base64,R0lGODlhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=">
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

document.getElementById('traffic').src=lights[lightCounter];之后,您需要if (lightCounter==3) lightCounter=0;,因为当您的循环超过4时,数组中只有4个元素。

答案 1 :(得分:0)

您可以使用remainder operator循环播放数组:

  

当一个操作数除以第二个操作数时,余数运算符返回剩余的余数。

所以,假设你的数组是:

var lights = ["red", "orangered", "green", "orange"]

如果你这样做:

lights[lightCounter % 4]

对于增加lightCounter,您将拥有以下指数:0,1,2,3,0,1,2,3,0,1,2,3等...... < / p>

&#13;
&#13;
var red = "data:image/gif;base64,R0lGODlhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=",
    redorange = "data:image/gif;base64,R0lGODlhAQABAIABAP9aAAAAACwAAAAAAQABAAACAkQBADs=",
    green = "data:image/gif;base64,R0lGODlhAQABAIABAAD/AAAAACwAAAAAAQABAAACAkQBADs=",
    orange = "data:image/gif;base64,R0lGODlhAQABAIABAP+qAAAAACwAAAAAAQABAAACAkQBADs=";

var lights = [red, redorange, green, orange];
var lightCounter = 0;

function pictureChange(){
  lightCounter += 1;
  document.getElementById('traffic').src = lights[lightCounter % 4];
}
&#13;
h1 {
  text-align: center;
}

img {
  display: block;
  margin: 0 auto;
}
&#13;
<h1><b> Traffic Lights </b></h1>

<center>
  <button onclick="pictureChange()">Change Lights</button>
</center>

<br><br>

<img width="230" height="400" id="traffic" src="data:image/gif;base64,R0lGODlhAQABAIABAP8AAAAAACwAAAAAAQABAAACAkQBADs=">
&#13;
&#13;
&#13;