自动化图像阵列

时间:2017-02-17 14:11:00

标签: javascript arrays image

我需要自动化一系列红绿灯,所以它们从红色到红色 - 琥珀色到绿色再到琥珀色本身,任何帮助?

这是我现在的代码

<!DOCTYPE html>
<html>
    <body>
        <style type="text/css">
            #box {
                text-align: center;
                font-size: 20px;
                vertical-align: middle;
                display: inline-block;
                min-width: 100px;
                min-height: 30px;
                padding: 10px;
                background-color: #FFF;
            }
        </style>

        <body>
            <img id="light" src="Traffic_Light_Red.png">
            <button type="button" onclick="changeLights()">Click to Change The Light Sequence</button>
            <script>
                var list = [
                    "Traffic_Light_Red.png",
                    "Traffic Light Red And Yellow Only.png",
                    "Traffic Light Green Only.png",
                    "Traffic Light Yellow Only.png"
                ];

                var index = 0;

                function changeLights() {
                index = index + 1;

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

                var image = document.getElementById('light');

                image.src=list[index];
            }

            </script>
        }
        </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

如果图像文件名列表转换为有效的URL,则代码应该有效。

您应该在结束</body>标记之前删除两个标记:

}
</script>

但它们不应该是图像不出现的原因。

以下演示代码:

var list = [
  "Traffic_Light_Red.png",
  "Traffic Light Red And Yellow Only.png",
  "Traffic Light Green Only.png",
  "Traffic Light Yellow Only.png"
  ];

var index = 0;

function changeLights() {
  var image = document.getElementById('light');
  var desc = document.getElementById('description');
  index = index + 1;
  if (index == list.length) {
    index = 0;
  }
  
  image.src = list[index];
  // for demo purposes
  desc.innerHTML = image.src;
}
#light {
  width: 25px;
  height: 25px;
  display: block;
  margin: 25px;
  background-color: #fee;
}

button {
  padding: 15px;
}

#description {
  width: 400px;
  height: 50px;
  margin: 10px;
}
<img id="light" src="Traffic_Light_Red.png">

<button type="button" onclick="changeLights()">Click to Change The Light Sequence</button>

<div id="description"></div>