![](/img/trans.png)
[英]How can I change the present image of the button to another image on button press in react-native
[英]How can i make the image change 3 times with only 1 button press?
必須按下按鈕3次才能使圖像改變3次。 我該怎么做,使按鈕僅被按下一次,但仍會更改圖像三次?
<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>
您可以在回調中使用此函數。.其中6是運行次數,而1000是更改之間的延遲..您顯然可以根據需要進行更改。
function change3(){ for(i=0;i<6;i++){ setTimeout(changeImage, 1000*i) } }
您可以使用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>
正如其他人所提到的,您希望查看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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.