【问题标题】:Toggle multiple elements with same class切换具有相同类的多个元素
【发布时间】:2020-08-15 15:26:33
【问题描述】:

我在网上找到了很多关于此的信息,但我似乎无法获得任何信息。

我正在尝试制作一个按钮,在单击时切换浅色/深色主题,仅更改正文背景颜色和页面上三个模式按钮的样式。我的代码适用于按钮样式,但不适用于正文背景。我很新手,所以我想我可能只是在语法上遗漏了一些东西。啊!

它需要使用原生 javascript 而不是 jQuery。任何提示将不胜感激。提前非常感谢!

CSS:

.light body {
    background: #D8DDDE;
}

.light .myBtn {

    color:rgb(58, 57, 57);
    background-color: #D8DDDE;
    border-top: solid 4px rgb(58, 57, 57);
    border-left: none;
    border-right: none;
    border-bottom: none; 
    transition: 0.6s;

}

Javascript

var themeSwitch = document.querySelector("footer button");

document.querySelector("footer button").addEventListener("click", toggleText);
   function toggleText() {
      if (themeSwitch.textContent === "Turn the lights off") {
         themeSwitch.textContent = "Turn the lights on";
      } else {
         themeSwitch.textContent = "Turn the lights off";
      }
   }

themeSwitch.addEventListener('click', function(){
    document.querySelector("body").classList.toggle("light") //this is working for the button but not the body background
})

【问题讨论】:

  • 请展示您的 HTML 代码并制作可运行的代码..
  • 在你的 CSS 中尝试body.light(没有空格)而不是.light body

标签: javascript css toggle


【解决方案1】:

此代码错误

  .light body {
        background: #D8DDDE;
    }

请改成

body.light{
    background: #D8DDDE;
} 

var themeSwitch = document.querySelector(".footer button");

themeSwitch.addEventListener("click", toggleText);
   function toggleText() {
      if (themeSwitch.textContent === "Turn the lights off") {
         themeSwitch.textContent = "Turn the lights on";
      } else {
         themeSwitch.textContent = "Turn the lights off";
      }
   }

themeSwitch.addEventListener('click', function(){
    document.querySelector("body").classList.toggle("light") //this is working for the button but not the body background
})
body.light {
    background: #D8DDDE;
}

.light .myBtn {

    color:rgb(58, 57, 57);
    background-color: #D8DDDE;
    border-top: solid 4px rgb(58, 57, 57);
    border-left: none;
    border-right: none;
    border-bottom: none; 
    transition: 0.6s;

}
<div class="footer">
<button>Turn the lights on</button>
</div>

【讨论】:

  • @imo-vee 试试这个你在body.light 类中添加了 stye 错误使用
【解决方案2】:

尝试从 css 类 .light 中删除 body

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    相关资源
    最近更新 更多