首页 > 解决方案 > 应用暗模式时本地存储不工作

问题描述

我正在尝试将暗模式应用到我的网站。我正在使用下面给出的代码来做到这一点。

!(function () {
  var t,
    e = document.getElementById("darkSwitch");
  if (e) {
    (t =
      null !== localStorage.getItem("darkSwitch") &&
      "dark" === localStorage.getItem("darkSwitch")),
      (e.checked = t)
        ? document.body.setAttribute("data-theme", "dark")
        : document.body.removeAttribute("data-theme"),
      e.addEventListener("change", function (t) {
        e.checked
          ? (document.body.setAttribute("data-theme", "dark"),
            localStorage.setItem("darkSwitch", "dark"))
          : (document.body.setAttribute("data-theme", "light"),
            localStorage.setItem("darkSwitch", "dark"));
      });
  }
})();

你可以在这里查看http://anayaadventure.com/

一切正常,但问题是现在假设我关闭暗模式并刷新页面,然后页面再次以暗模式加载。为什么会发生这种情况,我该如何解决。

感谢您提前提供任何帮助。

标签: javascripthtmlcss

解决方案


看起来您从未在切换事件中将 localstorage 设置回“light”

   e.checked
      ? (document.body.setAttribute("data-theme", "dark"),
        localStorage.setItem("darkSwitch", "dark")) //set to dark
      : (document.body.setAttribute("data-theme", "light"),
        localStorage.setItem("darkSwitch", "dark")); //set item to "light" instead of "dark" ?

如果您手动将本地存储值编辑为“light”,它会返回到 lightmode,所以我认为您想将最后一行更改为 localStorage.setItem("darkSwitch", "light"));

除此之外,我喜欢网站的布局和设计!


推荐阅读