首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在jquery中添加和删除类?

如何在jquery中添加和删除类?
EN

Stack Overflow用户
提问于 2020-06-28 08:58:32
回答 2查看 41关注 0票数 0

我正在尝试做一个按钮来将我的页面转到深色模式,我遇到了问题,当我将我的页面更改为深色模式,然后将其更改为浅色模式时,它只在第一次工作,但我再次尝试将其更改为深色模式,它什么也不做

这是我的darkmode.js

代码语言:javascript
运行
复制
const active = "light";

$("#btn-darkmode").click(function () {
  this.active = "dark";
  if (this.active === "dark") {
    $(".container-fluid").addClass("dark-mode");
    console.log("dark");
  }
  $(this).click(function () {
    this.active = "light";
    if (this.active === "light")
      $(".container-fluid").removeClass("dark-mode");
    console.log("light");
  });
});

这是我的index.html

代码语言:javascript
运行
复制
<span>Light</span>
<label class="switch">
  <input type="checkbox" id="btn-darkmode">
  <span class="slider round"></span>
</label>
<span>Dark</span>

更新index.css

代码语言:javascript
运行
复制
.dark-mode {
  background-color: black;
  color: white;
}
EN

回答 2

Stack Overflow用户

发布于 2020-06-28 09:15:25

我不确定您的代码出了什么问题,但我使用了toggleClass,它正在工作

代码语言:javascript
运行
复制
$('#btn-darkmode').on('click', function(){
  $('.container-fluid').toggleClass('dark-mode');
});
代码语言:javascript
运行
复制
.dark-mode {
  background-color: black;
  color: white;
}
代码语言:javascript
运行
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid">
<span>Light</span>
<label class="switch">
  <input type="checkbox" id="btn-darkmode">
  <span class="slider round"></span>
</label>
<span>Dark</span>
</div>

票数 1
EN

Stack Overflow用户

发布于 2020-06-28 09:50:22

有更简单的方法来实现同样的事情,但我修改了您的代码以使其工作。

代码语言:javascript
运行
复制
    let active = "light"; /* changing const to let, const means constant so doesn't have to change it's value once its already set */

    $("#btn-darkmode").click(function () {
      //this.active = "dark"; removed this line, and we'll use the one defined outside this function call
      if (active === "light") { /* change dark  to -> light makes more sense */
        $(".container-fluid").addClass("dark-mode");
        active = "dark"; /* add this line to set the new value of the current state */
        console.log("dark");
      }else if(active === "dark"){ /* you could use only 'else' instead, because there are only two states */
        $(".container-fluid").removeClass("dark-mode");
         active = "light";
         console.log("light");
      }
      //remove this block because it's a nested event handler function, and it's creating conflicts.
      /*$(this).click(function () { 
        this.active = "light";
        if (this.active === "light")
          $(".container-fluid").removeClass("dark-mode");
        console.log("light");
      }); */ 

    });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62617079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档