如何在深色模式切换功能中使用localStorage保存用户主题偏好
解决方案
核心问题定位
- 切换深色模式时错误调用了不存在的
localStorage.toggled()方法,导致深色模式偏好未能写入本地存储 - 缺少页面初始化时读取本地存储主题的逻辑,即使存储成功,刷新页面后配置也不会生效
修复代码
直接替换原有JavaScript代码即可:
// DOM加载完成后初始化主题 window.addEventListener('DOMContentLoaded', () => { // 读取本地存储的主题,无存储值时默认使用浅色模式 const savedTheme = localStorage.getItem('data-theme') || 'light'; document.body.setAttribute('data-theme', savedTheme); // 同步切换按钮图标状态 const nightIcon = document.getElementById('night'); const lightIcon = document.getElementById('light'); if (savedTheme === 'dark') { nightIcon.style.display = 'block'; lightIcon.style.display = 'none'; } else { nightIcon.style.display = 'none'; lightIcon.style.display = 'block'; } }) function toggleDark() { const container = document.body; const currentTheme = container.getAttribute('data-theme'); const nightIcon = document.getElementById('night'); const lightIcon = document.getElementById('light'); if (currentTheme === 'light') { container.setAttribute('data-theme', 'dark'); nightIcon.style.display = 'block'; lightIcon.style.display = 'none'; // 修正存储方法为setItem localStorage.setItem('data-theme', 'dark'); } else { container.setAttribute('data-theme', 'light'); nightIcon.style.display = 'none'; lightIcon.style.display = 'block'; localStorage.setItem('data-theme', 'light'); } }
内容的提问来源于stack exchange,提问作者Julen Sanchez
相关产品推荐
相关产品推荐

