如何在香草Javascript中使用toggle()方法压缩3 IF循环?



我已经创建了这个灯泡练习,它切换灯泡的SRC,背景颜色以及文本的颜色。作为一个额外的挑战,我试图看看我是否可以使用toggle()方法压缩我的代码,因为我有3个独立的函数。有没有人知道这是可能的,我怎么才能做到这一点?

<h1 class="title-text" id="title-text">Click the lightbulb to turn it on or off!</h1>
        <img id="lightbulb" onclick="toggleLight();toggleColor();toggleText()" src="/personal-projects/pic_bulbon1.gif">
        <script>
            let lightbulb = document.getElementById("lightbulb");
            let titleText = document.getElementById("title-text");
            
            function toggleLight() {
                if (lightbulb.src.match("bulbon1")) {
                    lightbulb.src = "/personal-projects/pic_bulboff1.gif"
                } else {
                    lightbulb.src = "/personal-projects/pic_bulbon1.gif"
                }
            }
            function toggleColor() {
                if (lightbulb.src.match("bulboff1")) {
                    document.body.style.background = "black";
                } else {
                    document.body.style.background = "#FEDD00";
                }
            }
            function toggleText() {
                if (lightbulb.src.match("bulboff1")) {
                    titleText.style.color = "white";
                } else {
                    titleText.style.color = "black";
                }
            }
        </script>
    </body>
</html>

If循环工作良好。如果可能的话,我只是想知道如何使用toggle。我找到的所有这类教程都涉及jquery。

使用切换方法

首先要在css中创建一个用于切换的类。您想要切换的每个元素都应该具有默认状态和切换状态。切换将添加/删除单个类。

参见下面的代码片段

片段
const LightBulb = document.getElementById("lightbulb");
const toggleLight = () => {
  LightBulb.classList.toggle("lightBulbOn");
  document.body.classList.toggle("bodyLightOn");
};
body {
  background-color: black;
}
body,
body .title-text {
  color: white;
}
body.bodyLightOn {
  background-color: #fedd00;
}
body.bodyLightOn .title-text {
  color: black;
}
#lightbulb::before {
  content: url("https://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/Gluehlampe_01_KMJ.png/340px-Gluehlampe_01_KMJ.png");
}
.lightBulbOn::before {
  content: url("https://cdn.mos.cms.futurecdn.net/HaPnm6P7TZhPQGGUxtDjAg-320-80.jpg") !important;
}
<h1 class="title-text" id="title-text">Click the lightbulb to turn it on or off!</h1>
<div id="lightbulb" class="" onclick="toggleLight();">
</div>

Codepen

最新更新