自动打开和关闭灯使用Javascript

时间:2016-03-28 16:29:15

标签: javascript html

当我点击灯泡时,它会打开和关闭,灯泡是否有自动打开和关闭的方式?

<!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>

1 个答案:

答案 0 :(得分:1)

您应该使用设置间隔功能。这将以设定的速率重复调用所述功能。

Mozilla Documentation

我展示的这个特定示例每1000毫秒或每秒调用一次changeImage函数。

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;