以下是我的代码......它的工作原理非常好但是......
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<img id="trafficlights" src="Redlight.jpeg" style="width:128px;height:128px;">
<button type="button" onclick="changetrafficlights()">Change Traffic Lights</button>
<script>
var position = 0;
var list = ["Redlight.jpeg","RedAmberlight.jpeg","Greenlight.jpeg", "Amberlight.jpeg"];
function changetrafficlights()
{position = position + 1;
if(position == list.length){
position = 0;
}
var image = document.getElementById('trafficlights');
image.src=list[position];}
</script>
</body>
</html>
我试图制作一个javascript代码,其中将使用while循环或for循环,其中将遍历变量&#34; list&#34;自动
答案 0 :(得分:0)
您可以通过以下方式使用setInterval()
:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<img id="trafficlights" src="Redlight.jpeg" style="width:128px;height:128px;">
<button type="button" onclick="starttrafficlights()">Change Traffic Lights</button>
<button type="button" onclick="stoptrafficlights()">Stop Traffic Lights</button>
<script>
var position = 1, id;
var list = ["Redlight.jpeg","RedAmberlight.jpeg","Greenlight.jpeg", "Amberlight"];
function changetrafficlights(){
stop = true;
var image = document.getElementById('trafficlights');
image.src=list[position % list.length];
position++;
}
function starttrafficlights(){
id = setInterval(changetrafficlights, 1000);
}
function stoptrafficlights(){
clearInterval(id);
}
</script>
</body>
</html>
这将在指定的持续时间后自动更改img
。
希望它能帮助!!