[英]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.