请用 CSS 变量实现“一键切换”深色模式并记住用户偏好

解读

国内前端面试中,深色模式已从“加分项”变成“必会项”。
技术文档工程师虽以写为主,但常需维护文档站点(VuePress、VitePress、Docusaurus、自建静态站)。
面试官想确认三点:

  1. 能否用纯前端方案(CSS 变量 + 原生 JS)快速落地,不依赖框架;
  2. 是否理解“系统偏好 → 用户手动选择 → 持久化”三级策略;
  3. 是否兼顾无障碍(prefers-color-scheme)与性能(避免闪屏)。
    答题时先给核心代码,再解释策略,最后补一句“可封装成文档主题插件”,既体现技术深度,又贴合岗位场景。

知识点

  1. CSS 自定义属性(变量)作用域与继承
  2. :root 与 data-theme 属性选择器权重
  3. window.matchMedia('(prefers-color-scheme: dark)') 事件
  4. localStorage 读写、JSON.stringify/parse 容错
  5. 页面加载前注入主题:将 JS 片段放 <head> 阻塞渲染,防止闪白
  6. 按钮状态同步:加载时就读取 localStorage,切换时更新按钮 aria-pressed
  7. 技术写作规范:变量命名用 kebab-case,注释写“用途+作者+日期”,方便后续交接

答案

<!-- index.html -->
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <title>文档站点深色模式示例</title>
  <!-- ① 关键:在 CSS 解析前把主题类写上去,避免闪屏 -->
  <script>
    (function(){
      const STORAGE_KEY = 'docs-theme';
      const media = '(prefers-color-scheme: dark)';
      const systemDark = window.matchMedia(media).matches;
      const saved = localStorage.getItem(STORAGE_KEY);
      // 三级回退:用户手动 > 系统 > 默认浅色
      const theme = saved ? saved : (systemDark ? 'dark' : 'light');
      document.documentElement.setAttribute('data-theme', theme);
    })();
  </script>

  <style>
    /* ② 用变量定义设计令牌 */
    :root {
      --color-bg: #ffffff;
      --color-text: #1f1f1f;
      --color-link: #0066cc;
      --code-bg: #f5f5f5;
    }

    /* ③ 深色覆盖 */
    [data-theme='dark'] {
      --color-bg: #121212;
      --color-text: #e5e5e5;
      --color-link: #66b3ff;
      --code-bg: #1e1e1e;
    }

    body {
      margin: 0;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif;
      background: var(--color-bg);
      color: var(--color-text);
      transition: background .2s, color .2s;
    }

    a { color: var(--color-link); }

    /* ④ 按钮样式 */
    .theme-toggle {
      position: fixed;
      top: 1rem;
      right: 1rem;
      padding: .5rem 1rem;
      border: 1px solid var(--color-text);
      background: transparent;
      color: var(--color-text);
      cursor: pointer;
      border-radius: 4px;
    }
  </style>
</head>

<body>
  <h1>技术文档示例</h1>
  <p>点击下方按钮切换深色/浅色模式,刷新后仍保持您的选择。</p>
  <button class="theme-toggle" id="toggleBtn" aria-pressed="false">🌗 切换主题</button>

  <script>
    const STORAGE_KEY = 'docs-theme';
    const btn = document.getElementById('toggleBtn');

    // ⑤ 初始化按钮状态
    function syncButton() {
      const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
      btn.setAttribute('aria-pressed', isDark);
      btn.textContent = isDark ? '🌙 深色模式' : '☀️ 浅色模式';
    }
    syncButton();

    // ⑥ 切换逻辑
    btn.addEventListener('click', () => {
      const current = document.documentElement.getAttribute('data-theme');
      const next = current === 'dark' ? 'light' : 'dark';
      document.documentElement.setAttribute('data-theme', next);
      localStorage.setItem(STORAGE_KEY, next);
      syncButton();
    });

    // ⑦ 监听系统偏好变化(可选)
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
      // 只有用户未手动选择时才自动跟随系统
      if (!localStorage.getItem(STORAGE_KEY)) {
        const next = e.matches ? 'dark' : 'light';
        document.documentElement.setAttribute('data-theme', next);
        syncButton();
      }
    });
  </script>
</body>
</html>

拓展思考

  1. 文档工程化:把上述逻辑抽成 vite-plugin-docs-theme,暴露 themeConfig: { default: 'light', respectPrefersColorScheme: true },让多位文档作者无需重复开发。
  2. SSR 场景:若站点用 Nuxt/Next,需在服务端读取 Cookie(localStorage 仅客户端),通过 Set-Cookie 把主题带回后端,避免 hydration 错位。
  3. 安全与无障碍:按钮加 aria-pressed 与 role="switch";CSS 变量值禁止用户输入,防止 CSS 注入。
  4. 性能:变量过多时可用 @layer 分层,减少重绘;对老旧浏览器可做 PostCSS 降级,将变量编译为静态值,保证国企内网 IE11 可读。