自动交通灯序列Javascript

时间:2017-03-03 12:50:53

标签: javascript html

我尝试了很多方法以使其工作但是我似乎无法让图像在设定的时间内自动更改,代码为:

<!DOCTYPE html>
<html>
    <body>
        <h1>JavaScript Task 3</h1>
        <p>This is my Traffic Light script</p>
        <img id="light" src="E:\A452\RED traffic light.jpg">
        <script>
        var list = [
            "RED AMBER traffic light.jpg",
            "GREEN traffic light.jpg",
            "AMBER traffic light.jpg",
            "RED traffic light.jpg"
        ];
        var index = 0;
        function changeLights() {
            index ++;
            if (index == list.length);
            index = 0;
            document.getElementById(light).src = list[index];
         }
         var timer = setInterval(changeLights,3000);
        </script>
    </body>
</html>

2 个答案:

答案 0 :(得分:2)

这里有一个错误:

document.getElementById('light').src = list[index]; // Needs ''

另请注意,当您的图像发生变化时,您将丢失图像src属性中的路径,因为它们未包含在灯光阵列中。

另外

if (index == list.length); 
    index = 0;

更改为

if (index == list.length) { 
    index = 0;
}

答案 1 :(得分:1)

老实说,我想知道结果是否应该只是视觉效果,或者它必须也是“功能性的”......你可以通过使用GIF(是的,不是最好的)或通过CSS - 本身不是你问题的答案。但了解您的选择可能会有所帮助。

@keyframes red {
  0% {background: red;}
  33% {background: red;}
  34% {background: black;}
  100% {background: black;}
}

@keyframes yellow {
  0% {background: black;}
  33% {background: black;}
  34% {background: yellow;}
  66% {background: yellow;}
  67% {background: black;}
  100% {background: black;}
}

@keyframes green {
  0% {background: black;}
  66% {background: black;}
  67% {background: green;}
  100% {background: green;}
}

.trafficLight {
  height: 120px;
  width: 40px;
  padding:3px;
  background:#CCC;
}

.trafficLight div {
  width: 90%;
  height: 30%;
  margin:7% auto;
  border-radius: 50%;
  animation-duration: 5s;
  animation-iteration-count: infinite;
}

.red {animation-name: red;}
.yellow {animation-name: yellow;}
.green {animation-name: green;}
.trafficLight, .trafficLight div{
  box-shadow:inset 5px 5px 5px rgba(255,255,255,.5),
             inset -5px -5px 5px rgba(0,0,0,.5);
}
<div class="trafficLight">
  <div class="red"></div>
  <div class="yellow"></div>
  <div class="green"></div>
</div>