【问题标题】:Using bootstrap4-toggle and localStorage to toggle CSS for dark mode使用 bootstrap4-toggle 和 localStorage 为深色模式切换 CSS
【发布时间】:2021-01-26 23:52:34
【问题描述】:

这必须非常简单;我正在尝试让 localStorage 与 Bootstrap 4 和附加库 bootstrap4-toggle https://github.com/gitbrent/bootstrap4-toggle 一起使用以切换 CSS 暗模式。

但是,dark这个类并没有添加到body-container div中,并且控制台没有错误,所以我不知道是什么坏了。

小提琴:https://jsfiddle.net/xn23e0ob/

图书馆:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js"></script>

HTML:

<label class="switch">
<input type="checkbox" data-toggle="toggle" onclick="darkLight()" id="checkBox">
<span class="slider"></span>
</label>

<div class="body-container">
div div 
</div>

功能:

$('.body-container').toggleClass(localStorage.toggled);

function darkLight() {
  if (localStorage.toggled != 'dark') {
    $('.body-container').toggleClass('dark', true);
    localStorage.toggled = "dark";
     
  } else {
    $('.body-container').toggleClass('dark', false);
    localStorage.toggled = "";
  }
}

CSS:

.dark {
  background-color: #000000 !important;
}

【问题讨论】:

    标签: jquery bootstrap-4 local-storage


    【解决方案1】:

    问题在于输入处理程序。它应该是onchange="darkLight()" 而不是onclick="darkLight()"

    【讨论】:

    • 谢谢!那很简单。我的简单错误。
    猜你喜欢
    • 2023-01-04
    • 1970-01-01
    • 2018-12-03
    • 2020-05-07
    • 2021-10-11
    • 2021-05-01
    • 2021-04-18
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多