暗色模式不是玄学,核心是 CSS 变量 + 一个 toggle + localStorage 记住偏好。
:root { --bg:#fff; --fg:#222; }
body.dark { --bg:#1a1a1a; --fg:#eee; }
JS 只做两件事:切换 body.dark 类、把选择存进 localStorage,刷新后读回来。
document.getElementById('toggle').onclick = () => {
const next = document.body.classList.contains('dark') ? 'light' : 'dark';
localStorage.setItem('theme', next);
document.body.classList.toggle('dark', next === 'dark');
};
附件 darkmode.zip 是可直接打开的完整组件,拿去改配色就能用。
楼主 · 2026-09-26 14:12 · 浏览 274
· 编辑于 2026-09-26 14:12

