如何使用CSS文件配置深色主题并通过JavaScript切换配色
问题解答
结论
完全可以实现,你目前把所有配色变量都统一挂载到:root根节点的写法,刚好适配JS动态修改CSS自定义属性的实现方案,不需要改动原有CSS结构就能完成主题切换。
具体实现步骤
- 第一步:先在页面导航栏加一个主题切换触发按钮,放在nav的
.items区域里即可:
<button id="themeToggle" style="background:none;border:none;color:#fff;cursor:pointer;font-size:16px;margin-left:10px;"> <i class="fas fa-moon"></i> 切换主题 </button>
- 第二步:在页面
</body>标签前加入JS逻辑,实现主题切换、参数持久化功能:
// 定义两套主题配置 const themeConfig = { light: { '--headerBG': '#222', '--headerColor': '#fff', '--codeBoxBG': '#333', '--codeBoxColor': '#fff', '--codeHeaderBG': '#121212', '--codeColor': '#fff', '--bodyBG': '#ccc', '--bodyColor': '#000', '--linkColor': '#ccc', '--linkHover': '#000' }, dark: { '--headerBG': '#222', '--headerColor': '#fff', '--codeBoxBG': '#222', '--codeBoxColor': '#fff', '--codeHeaderBG': '#121212', '--codeColor': '#fff', '--bodyBG': '#333', '--bodyColor': '#fff', '--linkColor': '#e7e7e7', '--linkHover': '#fff' } } // 切换主题的核心函数 function setTheme(themeName) { const root = document.documentElement const theme = themeConfig[themeName] // 遍历主题变量,批量修改根节点的CSS变量值 Object.keys(theme).forEach(key => { root.style.setProperty(key, theme[key]) }) // 把当前选中的主题存到本地存储,刷新页面不会丢失配置 localStorage.setItem('currentTheme', themeName) } // 页面加载时自动应用上次保存的主题,默认用浅色主题 const savedTheme = localStorage.getItem('currentTheme') || 'light' setTheme(savedTheme) // 绑定切换按钮的点击事件 const toggleBtn = document.getElementById('themeToggle') toggleBtn.addEventListener('click', () => { const currentTheme = localStorage.getItem('currentTheme') || 'light' const nextTheme = currentTheme === 'light' ? 'dark' : 'light' setTheme(nextTheme) // 同步切换按钮的图标显示 toggleBtn.querySelector('i').className = nextTheme === 'light' ? 'fas fa-moon' : 'fas fa-sun' })
额外说明
你原有样式里给所有元素加了transition: all .2s ease-in-out的过渡属性,切换主题的时候所有配色会自动带渐变过渡效果,不需要额外修改样式。
内容的提问来源于stack exchange,提问作者ADMI
相关产品推荐
相关产品推荐

