首页 > 解决方案 > 如何打开和关闭 bul:但仅使用 1 个按钮?

问题描述

这是来自 w3schools 的代码。我想用同一个按钮打开和关闭灯泡。尽可能简单。感谢每个答案:)

<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>


<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>
</html>

标签: javascript

解决方案


这是一种方法。

// Add an on-click handler to the button
document.getElementById("action-btn").onclick = (e) => {
    // Get the image
    let image = document.getElementById("myImage");
    // Check for the word "off"
    if (image.src.includes("off")) {
        // Set image to alternate
        image.src = "pic_bulbon.gif";
        // Set text of button
        e.srcElement.textContent = "Turn off the light";
    }
    else {
        image.src = "pic_bulboff.gif";
        e.srcElement.textContent = "Turn on the light";
    }
}
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<button id="action-btn">Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">


推荐阅读