【问题标题】:How can i make the image change 3 times with only 1 button press?如何仅按 1 个按钮使图像更改 3 次?
【发布时间】:2016-01-17 17:38:43
【问题描述】:
必须按三次按钮才能使图像更改三次。我怎样才能让它只按一次按钮,但它仍然会改变图像三次?
<body>
<h1>Traffic Light</h1>
<br>
<img id="myImage" src="Traffic_green.png" width="100" height="400">
<br>
<button type="button" onclick="changeImage()">Traffic light</button> //when clicked it runs function changeImage()
<br>
<p>Click to make the traffic light work</p>
</body>
【问题讨论】:
标签:
javascript
html
if-statement
button
【解决方案1】:
您可以在回调中使用此函数.. 其中 6 是运行次数,1000 是更改之间的延迟.. 您显然可以根据需要更改它们。
function change3(){
for(i=0;i<6;i++){
setTimeout(changeImage, 1000*i)
}
}
【解决方案2】:
您可以使用setTimeout 在 1500 毫秒(1.5 秒)后循环浏览其他图像:
<body>
<script>
function changeImage() {
var lightDelay = 1500; // delay between lights
var image = document.getElementById('myImage');
if (image.src.match("Traffic_green")) {
image.src = "Traffic_red.png"; // changes image from green to red traffic light
setTimeout(function() {
image.src = "Traffic_yellow.png"; // changes image from red to yellow traffic light
setTimeout(function() {
image.src = "Traffic_green.png"; //changes image from red to yellow traffic light
}, lightDelay)
}, lightDelay)
}
}
</script>
<h1>Traffic Light</h1>
<br>
<img id="myImage" src="Traffic_green.png" width="100" height="400">
<br>
<button type="button" onclick="changeImage()">Traffic light</button>//when clicked it runs function changeImage()
<br>
<p>Click to make the traffic light work</p>
</body>
【解决方案3】:
正如其他人所说,您想查看setTimeout。我也会使用clearTimeout,因此如果您继续单击按钮,超时不会叠加。试试这个:
<script>
var timerId;
function buttonClick() {
var count = 0;
// Cancel any currently running sequence
if(timerId) {
clearTimeout(timerId);
}
// Inner function to change after 3 secs and run again if needed
function doChange() {
timerId = setTimeout(function() {
if(count++ < 3) {
changeImage();
doChange();
}
}, 3000);
}
// Start the sequence
doChange();
}
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("Traffic_green")) {
image.src = "Traffic_red.png"; //changes image from green to red traffic light
} else if (image.src.match("Traffic_red")) {
image.src ="Traffic_yellow.png"; //changes image from red to yellow traffic light
} else {
image.src ="Traffic_green.png"; //changes image from red to yellow traffic light
}
}
</script>
<body>
<h1>Traffic Light</h1>
<br>
<img id="myImage" src="Traffic_green.png" width="100" height="400" style="background-color: green">
<br>
<button type="button" onclick="buttonClick()">Traffic light</button> //when clicked it runs function changeImage()
<br>
<p>Click to make the traffic light work</p>
</body>