Javascript交通灯 [英] Javascript Traffic light

查看:58
本文介绍了Javascript交通灯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<!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函数实现到该函数中时,灯光仅从红色-黄色-绿色-红色改变.谢谢您的帮助!

Hi, I am trying to make an animation script using JavaScript so that a traffic light sequence changes from red - yellow - green - yellow on a timer once a button is pressed. I only want the sequence to loop once. However, when I implemented the setInterval function into the function, the lights only change from red - yellow - green - red. Thank you for any help!

推荐答案

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);
  }
}

<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>

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

这篇关于Javascript交通灯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆