这是一个完整的深色/浅色主题切换组件,包含以下特性:
<!-- 主题切换按钮 -->
<button id="theme-toggle" class="theme-toggle" onclick="toggleTheme()" aria-label="Toggle dark mode">
<!-- 太阳图标 (浅色模式显示) -->
<svg class="theme-icon sun-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="5"></circle>
<line x1="12" y1="1" x2="12" y2="3"></line>
<line x1="12" y1="21" x2="12" y2="23"></line>
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
<line x1="1" y1="12" x2="3" y2="12"></line>
<line x1="21" y1="12" x2="23" y2="12"></line>
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
</svg>
<!-- 月亮图标 (深色模式显示) -->
<svg class="theme-icon moon-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
</svg>
</button>
请查看本页面的 <style> 标签获取完整的 CSS 代码
主要包含:
:root
- CSS 变量定义(浅色模式)body.dark-mode
- CSS 变量定义(深色模式).theme-toggle
- 按钮样式.theme-icon
- 图标通用样式.sun-icon / .moon-icon
- 图标状态控制// 初始化主题
function initTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
if (savedTheme === 'dark') {
document.body.classList.add('dark-mode');
}
}
// 切换主题
function toggleTheme() {
document.body.classList.toggle('dark-mode');
const isDark = document.body.classList.contains('dark-mode');
localStorage.setItem('theme', isDark ? 'dark' : 'light');
}
// 页面加载时初始化主题
initTheme();
步骤 1: 复制本文件中的 CSS 代码到您的样式表
步骤 2: 复制 HTML 按钮代码到您想要放置主题切换按钮的位置
步骤 3: 复制 JavaScript 代码到您的脚本文件或 <script> 标签中
步骤 4: 为您网站的其他元素添加深色模式样式(参考本页面的样式)
自定义颜色:
修改 :root
和 body.dark-mode
中的 CSS 变量即可轻松自定义颜色主题
点击右上角的主题切换按钮,体验浅色/深色模式切换效果!
当前主题会自动保存到浏览器本地存储,刷新页面后会保持您选择的主题。