动手:深色模式切换
你要做什么
一个切换按钮,点击转换为深色/浅色,刷新后记住选择。
⏱️ 15 分钟 | 🛠️ CSS 变量 + localStorage
跟着做
帮我实现一个深色模式切换功能:
1. 页面右上角有一个太阳/月亮图标切换按钮
2. 点击切换整个页面的深色/浅色主题
3. 使用 CSS 变量管理颜色(--bg, --text, --surface 等)
4. 用 localStorage 记住用户选择,刷新后保持一致
5. 首次访问时读取系统的深色/浅色偏好
理解实现
AI 会生成类似这样的结构:
:root {
--bg: #ffffff;
--text: #1e1e2e;
}
[data-theme="dark"] {
--bg: #0f0f1a;
--text: #e8eaf0;
}
const theme = localStorage.getItem('theme') ||
(window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
document.documentElement.setAttribute('data-theme', theme);
🎯 进阶挑战
- 加上切换动画(颜色渐变过渡)
- 支持 3 种模式:浅色/深色/跟随系统
- 把切换按钮做得更有设计感(旋转动画)
✅ 你做到了
- 掌握了 CSS 变量的主题切换
- 理解了 localStorage 持久化
- 学会了读取系统偏好设置