为暗模式添加本地存储(在 jquery 中)

问题描述 投票:0回答:2

我想为暗模式添加本地存储以记住用户的选择。 我已经阅读和查看了课程并尝试了不同的方法,但代码仍然无法正常工作,而且我不理解它。 非常感谢您的帮助和诚挚的问候! :)

jQuery

$(document).ready(function () {
  localStorage.getItem("theme")

    function isDark() {
        return $("html").attr("theme") == 'dark';
    }

    function darkModeToggle() {
        if (isDark()) {
            $("html").attr("theme", "light");
        }
        else {
            $("html").attr("theme", "dark");
        }
    }

    function onClickDark() {
        $('.theme-switcher').on('click', function () {
            darkModeToggle();
            if (isDark()) {
                $(this).addClass('active');
                localStorage.setItem("mode", "dark");    
            }
            else {
                $(this).removeClass('active');
                localStorage.setItem("mode", "light");
            }
        });
    }

    onClickDark();
});

HTML

<label class="theme-switcher">
            <span class="theme-switcher-label"> icons with sun and moon </span>
            <span class="theme-switcher-handle"></span>
</label>
jquery local-storage
2个回答
0
投票

我将向您展示下面的示例代码,以展示如何在 jQuery 中使用本地存储来实现深色模式,就像您想要的那样。

它只会让您了解其工作原理,但您可以删除我的样式和按钮,并根据自己的想法创建具有更多功能的自己的样式和按钮。

我还看到这是最专业的深色模式代码。

此代码只是切换按钮,单击它即可转换为深色模式,再次单击将转换为浅色模式并将其保存在本地存储中。并在启动时检查用户选择哪种方法。

// Get the theme toggle input
const themeToggle = document.querySelector(
  '.theme-switch input[type="checkbox"]'
);
// Function that will switch the theme based on the if the theme toggle is checked or not
function switchTheme(e) {
  if (e.target.checked) {
    document.documentElement.setAttribute("data-theme", "dark");
  } else {
    document.documentElement.setAttribute("data-theme", "light");
  }
}
// Add an event listener to the theme toggle, which will switch the theme
themeToggle.addEventListener("change", switchTheme, false);
function switchTheme(e) {
  if (e.target.checked) {
    document.documentElement.setAttribute("data-theme", "dark");
    
    // Set the user's theme preference to dark
    localStorage.setItem("theme", "dark");
  } else {
    document.documentElement.setAttribute("data-theme", "light");
    
    // Set the user's theme preference to light
    localStorage.setItem("theme", "light");
  }
}
// Get the current theme from local storage
const currentTheme = localStorage.getItem("theme");
// If the current local storage item can be found
if (currentTheme) {
  // Set the body data-theme attribute to match the local storage item
  document.documentElement.setAttribute("data-theme", currentTheme);
// If the current theme is dark, check the theme toggle
  if (currentTheme === "dark") {
    themeToggle.checked = true;
  }
}
:root {
  --bg-color: #fec150;
  --font-color: #222;
  --title-color: #0067e6;
  --title-background: #fff;
  --main-border: 1px solid rgba(255, 255, 255, 0.4);
  --main-bg: rgba(255, 255, 255, 0.4);
}
[data-theme="dark"] {
  --bg-color: #111;
  --font-color: #efefef;
  --title-color: #fec150;
  --title-background: #222;
  --main-border: 1px solid rgba(255, 255, 255, 0.2);
  --main-bg: rgba(25, 25, 25, 0.4);
}
body {
  color: var(--font-color);
  background-color: var(--bg-color);
/* OTHER STYLING */
  ...
}
main {
  border: var(--main-border);
  background: var(--main-bg);
/* OTHER STYLING */
  ...
}
h1 {
  color: var(--title-color);
/* OTHER STYLING */
  ...
}
.theme-switch-wrapper {
  display: flex;
  align-items: center;
}
.theme-switch-wrapper em {
  margin-left: 10px;
  font-size: 1rem;
}
.theme-switch {
  display: inline-block;
  height: 34px;
  position: relative;
  width: 60px;
}
.theme-switch input {
  display: none;
}
.slider {
  background-color: #ccc;
  bottom: 0;
  cursor: pointer;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  transition: 0.4s;
  border-radius: 34px;
}
.slider:before {
  background-color: #fff;
  bottom: 4px;
  content: "";
  height: 26px;
  left: 4px;
  position: absolute;
  transition: 0.4s;
  width: 26px;
  border-radius: 50%;
}
input:checked + .slider {
  background-color: #fec150;
}
input:checked + .slider:before {
  transform: translateX(26px);
}
.slider svg {
  color: #222;
  position: absolute;
  transition: opacity 0.2s ease 0s, transform 0.35s ease 0s;
  pointer-events: none;
}
.feather-moon {
  opacity: 0;
  left: 9px;
  bottom: 9px;
  transform: translateX(4px);
}
.feather-sun {
  opacity: 1;
  right: 10px;
  bottom: 9px;
  transform: translateX(0px);
}
input:checked + .slider .feather-moon {
  opacity: 1;
  transform: translateX(0);
}
input:checked + .slider .feather-sun {
  opacity: 0;
  transform: translateX(-4px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="theme-switch-wrapper">
  <label class="theme-switch" for="checkbox">
    <input type="checkbox" id="checkbox" />
    <div class="slider">
      <svgOfSun />
      <svgOfMoon />
    </div>
  </label>
</div>

注意:您可能会在控制台中看到错误,显示“未捕获的安全错误:无法从“窗口”读取“localStorage”属性:此文档的访问被拒绝。”

该错误的解决方案位于 here,其中包含适用于 Google Chrome 的完整方法。

感谢这篇文章,我从中找到了代码(https://blog.prototypr.io/create-your-own-dark-mode-using-js-css-variables-and-localstorage-8b461864644b)。


0
投票

当我看到这篇文章时,我正在寻找一种自己执行此操作的方法。然而,我的方法是使用链接而不是输入,所以我不得不想出另一种方法。我不确定这是否是一个完美的解决方案,但如果您更愿意使用可点击的链接,它就可以工作。

JS:

var html = document.querySelectorAll('html')[0];
var themeToggle = document.querySelectorAll('*[data-bs-toggle-theme]')[0];
if (localStorage.getItem('isDarkMode') === 'true') {
  html.setAttribute('data-bs-theme', 'dark');
} else {
  html.setAttribute('data-bs-theme', 'light');
}
if (themeToggle) {
  themeToggle.addEventListener('click', function(event) {
    event.preventDefault();

    if (html.getAttribute('data-bs-theme') === 'light') {
      html.setAttribute('data-bs-theme', 'dark');
      localStorage.setItem('isDarkMode', true);
    } else {
      html.setAttribute('data-bs-theme', 'light');
      localStorage.removeItem("isDarkMode");
    }
  });
}

HTML:

<a class="nav-link" href="#" tabindex="-1" data-bs-toggle-theme="true" aria-disabled="true">
  <i class="day-night"></i>
</a>
© www.soinside.com 2019 - 2024. All rights reserved.