页面刷新后localStorage存储的浅色主题重置回深色主题如何解决
问题根因
页面首次加载时没有读取localStorage中已存储的主题配置同步页面类名,刷新后浏览器只会渲染默认的深色样式,不会自动应用之前保存的浅色模式。
另外原有代码用localStorage.setItem("theme", null)存值存在bug:localStorage仅支持存储字符串类型,传入null会被自动转为字符串"null",后续判断逻辑会出现异常。
修复后完整代码
// 页面加载阶段第一时间读取已存储的主题配置 const savedTheme = localStorage.getItem("theme"); const lightModeToggle = document.querySelector(".moon-white"); const enableLightMode = () => { document.body.classList.add("light-theme"); localStorage.setItem("theme", "enabled"); }; const disableLightMode = () => { document.body.classList.remove("light-theme"); // 不需要存值时直接移除对应键,避免存null转成字符串的问题 localStorage.removeItem("theme"); }; // 初始化时如果存储的是浅色模式启用状态,立即应用样式 if (savedTheme === "enabled") { enableLightMode(); } // 绑定切换按钮点击事件 lightModeToggle.addEventListener("click", () => { const currentTheme = localStorage.getItem("theme"); currentTheme !== "enabled" ? enableLightMode() : disableLightMode(); });
优化提示
- 建议把主题初始化读取的逻辑放在HTML的
<head>标签内靠前位置执行,避免页面加载时先渲染默认深色、再切换成浅色的样式闪烁问题 - 所有存入
localStorage的值如果不需要了,优先用removeItem()方法删除,不要传null/undefined这类非字符串值,避免隐式类型转换导致的判断错误
内容的提问来源于stack exchange,提问作者Surge
相关产品推荐
相关产品推荐

