简体   繁体   English

使用 Javascript 自动开灯和关灯

[英]Automatically turning light on and off use Javascript

As I click On light bulb it turned on and off, Is there any way light bulb turn on and off automatically?当我点击打开灯泡时,它会打开和关闭,有没有办法让灯泡自动打开和关闭?

<!DOCTYPE html>
<html>
<body>
<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light.</p>
<script>
function changeImage() {
    var image = document.getElementById('myImage');
    if (image.src.match("bulbon")) {
        image.src = "pic_bulboff.gif";
    } else {
        image.src = "pic_bulbon.gif";
    }
}
</script>
</body>
</html>

You should use the set interval function.您应该使用设置间隔功能。 This will repeatedly call the stated function at a set rate.这将以设定的速率重复调用所述函数。

Mozilla Documentation Mozilla 文档

This specific example I show calls the changeImage function every 1,000 milliseconds, or every second.我展示的这个特定示例每 1,000 毫秒或每秒调用一次 changeImage 函数。

 <!DOCTYPE html> <html> <body> <img id="myImage" src="pic_bulboff.gif" width="100" height="180"> <p>Click the light bulb to turn on/off the light.</p> <script> function changeImage() { var image = document.getElementById('myImage'); if (image.src.match("bulbon")) { image.src = "pic_bulboff.gif"; } else { image.src = "pic_bulbon.gif"; } } setInterval(changeImage,1000); </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM