给博客加上深色模式
深色模式几乎是现代网站的标配。实现它最关键的两点是:主题变量化 和 避免闪白。
用 CSS 变量定义两套主题
在 :root 定义浅色变量,在 [data-theme='dark'] 下覆盖为深色:
:root {
--bg: #ffffff;
--text: #1a1a2e;
}
[data-theme='dark'] {
--bg: #0f1020;
--text: #ececff;
}
所有组件只引用变量,切换主题就只需要改 data-theme。
关键:首屏前同步设置主题
如果在页面加载后才用 JS 设置主题,会出现「浅色闪一下再变深色」的闪白。解决办法是在 <head> 里放一段 同步内联脚本,在绘制前就读取 localStorage 或系统偏好:
<script is:inline>
const t = localStorage.getItem('theme')
|| (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
document.documentElement.setAttribute('data-theme', t);
</script>
切换按钮
按钮点击时切换 data-theme 并写回 localStorage,刷新后依然保持。就这么简单。