Javascript交通灯

时间:2017-04-24 17:51:07

标签: javascript arrays

<!DOCTYPE>
<html>
<body>

<img id="traffic" src="assets/red.gif">

<button type="button" onclick="ChangeLights()">Change Lights</button>

<script>
var lights = [
	"assets/red.gif",
	"assets/yellow.gif",
	"assets/green.gif",
	"assets/yellow.gif",
];

var index = 0;

function ChangeLights() {

  setInterval(function () {ChangeLights();}, 1000);
  
	index = index + 1;
	
	if (index == lights.length) index = 0;
	
	var image = document.getElementById('traffic');
    image.src=lights[index];

}


</script>

</body>
</html>

嗨,我正在尝试使用JavaScript创建一个动画脚本,以便在按下按钮时,交通灯序列从红色 - 黄色 - 绿色 - 黄色变为计时器。我只希望序列循环一次。但是,当我在函数中实现setInterval函数时,灯光只会从红色 - 黄色 - 绿色 - 红色变为红色。 谢谢你的帮助!

5 个答案:

答案 0 :(得分:1)

&#13;
&#13;
var lights = {
  red: "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Traffic_lights_red.svg/200px-Traffic_lights_red.svg.png",
  yellow: "https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/Traffic_lights_yellow.svg/200px-Traffic_lights_yellow.svg.png",
  green: "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Traffic_lights_dark_green.svg/200px-Traffic_lights_dark_green.svg.png"
};

var sequence = ['red', 'yellow', 'green', 'yellow'];

function startChangeLights() {
  for (var index = 0; index < sequence.length; index++) {
    changeLight(index, sequence[index]);
  }

  function changeLight(index, color) {
    setTimeout(function() {
      var image = document.getElementById('traffic');
      image.src = lights[color];
    }, index * 1000);
  }
}
&#13;
<div>
  <img height=100px id="traffic" src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Traffic_lights_red.svg/200px-Traffic_lights_red.svg.png">
</div>
<div>
  <button type="button" onclick="startChangeLights()">Change Lights</button>
</div>
&#13;
&#13;
&#13;

https://codepen.io/anon/pen/VbKQNj?editors=1011

答案 1 :(得分:0)

如果您正在寻找一个时间序列,您必须在javascript中使用“setTimeout”方法,此外,定义如下内部函数:

var lights = [
	"assets/red.gif",
	"assets/yellow.gif",
	"assets/green.gif",
	"assets/yellow.gif",
];

var index = 0;

function ChangeLights() {

  
  function innerChangeLight(){
	index = index + 1;
	
	if (index == lights.length) index = 0;
	
	var image = document.getElementById('traffic');
    image.src=lights[index];
  }
  innerChangeLight();
  setTimeout(function () {
      innerChangeLight();
    }, 1000);
  
}
<!DOCTYPE>
<html>
<body>

<img id="traffic" src="assets/red.gif">

<button type="button" onclick="ChangeLights()">Change Lights</button>

</body>
</html>

答案 2 :(得分:0)

试试这个:

var lights = [
	"assets/red.gif",
	"assets/yellow.gif",
	"assets/green.gif",
	"assets/yellow.gif",
];

var index = 0;
function ChangeLights(){
  setInterval(function() {
    
    if(index == lights.length) {
      return;
    }
    var image = document.getElementById('traffic');
    image.src=lights[index];
    index = index + 1;
  }, 1000);
  
}
<img id="traffic" src="assets/red.gif"><br>
<button onclick="ChangeLights()">Change Lights</button>

答案 3 :(得分:0)

&#39;交通灯&#39;的新实例:

交通信号灯在每个灯光下的持续时间不能相同....

所以,我开始扩展这个HTML代码.. 改进的代码在每个灯光中都有不同的秒数:

&#13;
&#13;
// Traffic Light
// Improved with different durations in every light!
// But in this html code, i will use input tag instead
var TrafficLights = (function() {
  // The image   
  var imageTag = document.getElementById("lightImg");
  // Keep track of whether the sequence is running    
  var running = false;

  // Different stages of the traffic light (Also defines the light)    
  var stages = [
    {
      "name": "red",
      "path": "https://upload.wikimedia.org/wikipedia/commons/thumb/4/45/Traffic_lights_red.svg/200px-Traffic_lights_red.svg.png",
    },
    {
      "name": "green",
      "path": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Traffic_lights_dark_green.svg/200px-Traffic_lights_dark_green.svg.png"
    },
    {
      "name": "yellow",
      "path": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/Traffic_lights_yellow.svg/200px-Traffic_lights_yellow.svg.png"
    }
  ];

  // Different amount of seconds in every light change (Must be an positive integer!)
  var seconds_every_step = [
    18,
    24,
    3
  ];

  // Current stage of the traffic light 
  var stage = 0;
  // Current steps of the traffic light   
  var steps = 0;
  // Timer for automatically changing light    
  var timer = null;
  /**     * Start the traffic light sequence     *     */
  function start() {
    // Mark that the light sequence is running        
    running = true;
    // Tell the light to change        
    changeLight();
  }

  /**     * Stop the sequence from running     *     */
  function stop() {
    // Mark that the sequence is not running        
    running = false;
    // Stop the automatic timer from running        
    clearInterval(timer);
  }

  /**     * Change the light to the next one in the sequence     *     */
  function changeLight() {
    // If the timer is not running, this function does not need to do anything        
    if (running === false) {
      clearInterval(timer);
      return;
    } else {};

    // If the current stage gets higher than the number of stages there are, reset to 0        
    if (stage >= stages.length) {
      stage = 0;
    } else {};
    // If the current steps gets higher than the number of seconds in a step there are, reset to 0    
    if (steps >= seconds_every_step.length) {
      steps = 0;
    } else {};

    // Get the image from the list of stages        
    var image = stages[stage];
    var wait_seconds = seconds_every_step[steps];
    // Update the image tag and defines the light name
    imageTag.src = image.path;
    imageTag.alt = String("Traffic light color is " + image.name + ".");

    // Increase the current stage by 1        
    stage++;
    // Increase the current steps by 1        
    steps++;
    // Set a timeout to change the light at the next interval        
    timer = setTimeout(changeLight, wait_seconds * 1000);
  }
  // These functions will be available on the `TrafficLights` object to allow interaction    
  return {
    start: start,
    stop: stop
  }
})();
&#13;
<input type="image" width="20px" id="lightImg" src="" alt="">
<br/>
<p>
  <button type="button" onclick="TrafficLights.start()">Start Sequence</button> <button type="button" onclick="TrafficLights.stop()">Stop Sequence</button>
</p>
&#13;
&#13;
&#13;

您可能会看到错误代码。只是忽略它......

答案 4 :(得分:-2)

var red = document.getElementById("red");
var yellow = document.getElementById("yellow");
var green = document.getElementById("green");

var btn = document.createElement("BUTTON"); 
btn.innerHTML = "CLICK ME";                 
document.body.appendChild(btn);
red.style.opacity = "1";
yellow.style.opacity = "0.2";
green.style.opacity = "0.2";        

btn.onclick = function () {

   setTimeout(function(){red.style.opacity = "0.2";yellow.style.opacity = "1";   setTimeout(function(){yellow.style.opacity = "0.2";green.style.opacity = "1"; setTimeout(function(){green.style.opacity = "0.2";red.style.opacity = "1"}, 1000);}, 1000);
}, 1000);

 
}
html{
  background: linear-gradient(#08f, #fff);
  padding: 40px;
  width: 170px;
  height: 100%;
  margin: 0 auto;
}

.trafficlight{
  background: #222;
  background-image: linear-gradient(transparent 2%, #111 2%, transparent 3%, #111 30%);
  width: 170px;
  height: 400px;
  border-radius: 20px;
  position: relative;
  border: solid 5px #333;
}

#red{
  background: red;
  background-image: radial-gradient(brown, transparent);
  background-size: 5px 5px; 
  width: 100px;
  height: 100px;
  border-radius: 50%;
  position: absolute;
  top: 20px;
  left: 35px;
  animation: 13s red infinite;
  border: dotted 2px red;
  box-shadow: 
    0 0 20px #111 inset,
    0 0 10px red;
}

#yellow{
  background: yellow;
  background-image: radial-gradient(orange, transparent);
  background-size: 5px 5px;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: dotted 2px yellow;
  position: absolute;
  top: 145px;
  left: 35px;
  animation: 13s yellow infinite;
  box-shadow: 
    0 0 20px #111 inset,
    0 0 10px yellow;
}

#green{
  background: green;
  background-image: radial-gradient(lime, transparent);
  background-size: 5px 5px;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: dotted 2px lime;
  position: absolute;
  top: 270px;
  left: 35px;
  box-shadow: 
    0 0 20px #111 inset,
    0 0 10px lime;
  animation: 13s green infinite;
}
<div class="trafficlight">
  <div id="red"></div>
  <div id="yellow"></div>
  <div id="green"></div>
</div>

我根据在线示例制作了一个简单的 HTML 和 CSS 交通灯。然后我只是为它创建循环红-黄-绿-红的条件。