javascript - 应用暗模式时本地存储不工作
问题描述
我正在尝试将暗模式应用到我的网站。我正在使用下面给出的代码来做到这一点。
!(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/
一切正常,但问题是现在假设我关闭暗模式并刷新页面,然后页面再次以暗模式加载。为什么会发生这种情况,我该如何解决。
感谢您提前提供任何帮助。
解决方案
看起来您从未在切换事件中将 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"));
除此之外,我喜欢网站的布局和设计!
推荐阅读
- javascript - 根据文本长度和容器大小调整字体大小
- github - 如果 Git 中的多个远程存储库包含一个名称相同但数据不同的分支,我该如何处理它们?
- excel - ExportAsFixedFormat 为 PDF System.Runtime.InteropServices.COMException:
- r - 函数取决于 R 中的行中的值
- sql - 删除 SQL Server 查询中的前导 0
- python - Python re.match - 一个数字的成功匹配结果是一个字母?
- javascript - 如何将一小部分 Markdown 解析为 React 组件?
- ruby-on-rails - Rails + PostgreSQL:如何获取至少订购一次的产品+获取订单#和经理ID
- reactjs - 你如何在没有 babel 的情况下运行 reactjs
- python - python中的堆叠圆形条形图