feat: 增加暗黑主题切换功能 🌙
- CSS 变量实现主题切换 - 右上角切换按钮 - 本地存储记住主题偏好 - 平滑过渡动画 - 所有页面支持暗黑模式
This commit is contained in:
60
static/js/theme.js
Normal file
60
static/js/theme.js
Normal file
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* 暗黑主题切换功能
|
||||
* 小白制作 🐶
|
||||
*/
|
||||
|
||||
(function() {
|
||||
const themeKey = 'my_one_web_theme';
|
||||
|
||||
// 获取保存的主题
|
||||
function getSavedTheme() {
|
||||
return localStorage.getItem(themeKey) || 'light';
|
||||
}
|
||||
|
||||
// 保存主题
|
||||
function saveTheme(theme) {
|
||||
localStorage.setItem(themeKey, theme);
|
||||
}
|
||||
|
||||
// 应用主题
|
||||
function applyTheme(theme) {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
updateToggleButton(theme);
|
||||
}
|
||||
|
||||
// 更新切换按钮图标
|
||||
function updateToggleButton(theme) {
|
||||
const btn = document.querySelector('.theme-toggle');
|
||||
if (btn) {
|
||||
btn.textContent = theme === 'dark' ? '☀️' : '🌙';
|
||||
btn.setAttribute('aria-label', theme === 'dark' ? '切换到亮色模式' : '切换到暗黑模式');
|
||||
}
|
||||
}
|
||||
|
||||
// 切换主题
|
||||
function toggleTheme() {
|
||||
const currentTheme = getSavedTheme();
|
||||
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
|
||||
saveTheme(newTheme);
|
||||
applyTheme(newTheme);
|
||||
}
|
||||
|
||||
// 初始化主题
|
||||
function initTheme() {
|
||||
const savedTheme = getSavedTheme();
|
||||
applyTheme(savedTheme);
|
||||
|
||||
// 绑定切换按钮事件
|
||||
const btn = document.querySelector('.theme-toggle');
|
||||
if (btn) {
|
||||
btn.addEventListener('click', toggleTheme);
|
||||
}
|
||||
}
|
||||
|
||||
// DOM 加载完成后初始化
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', initTheme);
|
||||
} else {
|
||||
initTheme();
|
||||
}
|
||||
})();
|
||||
Reference in New Issue
Block a user