开关灯案例

Tutorial: DOM操作 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0
<!DOCTYPE html>
<html lang="en">
  <head> </head>

  <body>
    <button id="btn">开关灯</button>

    <script>
      var btn = document.getElementById("btn");
      var status = "on";

      btn.onclick = function () {
        if (status === "on") {
          document.body.style.backgroundColor = "black";
          status = "off";
        } else {
          document.body.style.backgroundColor = "#fff";
          status = "on";
        }
      };
    </script>
  </body>
</html>