fix: 修复移动端主题切换问题 📱
- 添加 z-index: 100 确保按钮在最上层 - 增加 touchstart/touchend 事件支持 - 添加 touch-action 优化触摸操作 - 增加 -webkit-tap-highlight 去除高亮 - 添加防抖机制避免重复触发 - 支持键盘操作(无障碍)
This commit is contained in:
@@ -4,16 +4,26 @@
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const themeKey = 'my_one_web_theme';
|
||||
|
||||
// 获取保存的主题
|
||||
function getSavedTheme() {
|
||||
return localStorage.getItem(themeKey) || 'light';
|
||||
try {
|
||||
return localStorage.getItem(themeKey) || 'light';
|
||||
} catch (e) {
|
||||
return 'light';
|
||||
}
|
||||
}
|
||||
|
||||
// 保存主题
|
||||
function saveTheme(theme) {
|
||||
localStorage.setItem(themeKey, theme);
|
||||
try {
|
||||
localStorage.setItem(themeKey, theme);
|
||||
} catch (e) {
|
||||
// localStorage 不可用时忽略
|
||||
}
|
||||
}
|
||||
|
||||
// 应用主题
|
||||
@@ -31,12 +41,28 @@
|
||||
}
|
||||
}
|
||||
|
||||
// 切换主题
|
||||
function toggleTheme() {
|
||||
// 切换主题(防抖)
|
||||
let isToggling = false;
|
||||
function toggleTheme(e) {
|
||||
// 阻止默认行为和冒泡
|
||||
if (e) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
|
||||
// 防抖:300ms 内只响应一次
|
||||
if (isToggling) return;
|
||||
isToggling = true;
|
||||
|
||||
const currentTheme = getSavedTheme();
|
||||
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
|
||||
saveTheme(newTheme);
|
||||
applyTheme(newTheme);
|
||||
|
||||
// 300ms 后重置
|
||||
setTimeout(function() {
|
||||
isToggling = false;
|
||||
}, 300);
|
||||
}
|
||||
|
||||
// 初始化主题
|
||||
@@ -47,7 +73,23 @@
|
||||
// 绑定切换按钮事件
|
||||
const btn = document.querySelector('.theme-toggle');
|
||||
if (btn) {
|
||||
// 点击事件
|
||||
btn.addEventListener('click', toggleTheme);
|
||||
|
||||
// 触摸事件(移动端)
|
||||
btn.addEventListener('touchstart', function(e) {
|
||||
e.preventDefault();
|
||||
}, { passive: false });
|
||||
|
||||
btn.addEventListener('touchend', toggleTheme, { passive: true });
|
||||
|
||||
// 键盘支持(无障碍)
|
||||
btn.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleTheme(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user