试一下代码
// 初始化主题时添加验证
function initTheme() {
const saved = localStorage.getItem('theme');
// 仅允许light/dark两种值,防止篡改
const validThemes = ['light', 'dark'];
const theme = validThemes.includes(saved) ? saved : getSystemTheme();
if (theme === 'dark') {
html.setAttribute('data-theme', 'dark');
themeBtn.textContent = '☀️';
} else {
html.removeAttribute('data-theme');
themeBtn.textContent = '🌙';
}
}
// 存储时添加验证
themeBtn.addEventListener('click', () => {
const isDark = html.hasAttribute('data-theme');
const newTheme = isDark ? 'light' : 'dark';
if (['light', 'dark'].includes(newTheme)) { // 验证值合法性
if (isDark) {
html.removeAttribute('data-theme');
themeBtn.textContent = '🌙';
} else {
html.setAttribute('data-theme', 'dark');
themeBtn.textContent = '☀️';
}
localStorage.setItem('theme', newTheme);
}
});
我好困
山峙