在深色模式下,如何为 CSS 变量提供即时切换而不重新加载样式?

解读

面试官真正想考察的是“无刷新主题切换”在企业级 Angular 项目中的落地能力。国内大厂(阿里、腾讯、字节、美团)的 B 端系统普遍要求:

  1. 秒级切换,禁止页面闪烁或重载;
  2. 主题可持久化(localStorage / Cookie),刷新后保持;
  3. 支持 SSR(Angular Universal)与水合,SEO 友好;
  4. 与 Angular 的 View Encapsulation、懒加载模块、第三方组件库(Ant Design Angular、Material)零冲突。

因此,回答必须围绕“CSS 变量 + 依赖注入 + RxJS 流 + DOM 无刷新更新”展开,并给出可落地的代码骨架。

知识点

  1. **CSS 自定义属性(变量)**的继承与优先级规则;
  2. Angular Renderer2 的安全 DOM 操作;
  3. APP_INITIALIZER 在 SSR 环境下预取主题;
  4. RxJS BehaviorSubject 实现全局主题流;
  5. document.documentElement.classList.toggle 的性能最优路径;
  6. ** prefers-color-scheme** 媒体查询与手动切换的并存策略;
  7. View Encapsulation.None 与 ::ng-deep 的取舍;
  8. 懒加载模块下 CSS 变量的延迟注入与 Shadow DOM 穿透;
  9. Angular Universal 水合时避免“FOUC”(Flash of Unstyled Content);
  10. 国内浏览器(360、QQ、UC)对 CSS 变量的兼容底线(Chrome 49+)。

答案

  1. 定义全局 CSS 变量文件 src/styles/themes.scss,使用 :root 与 [data-theme='dark'] 两套作用域:
:root {
  --brand-primary: #1890ff;
  --bg-base: #ffffff;
  --text-primary: #262626;
}
[data-theme='dark'] {
  --brand-primary: #177ddc;
  --bg-base: #141414;
  --text-primary: #e8e8e8;
}
  1. 创建 ThemeService 核心服务,利用 BehaviorSubject 提供流式切换:
@Injectable({ providedIn: 'root' })
export class ThemeService {
  private theme$ = new BehaviorSubject<'light' | 'dark'>('light');
  themeObs = this.theme$.asObservable();

  constructor(@Inject(DOCUMENT) private doc: Document) {
    const stored = localStorage.getItem('theme') as 'light' | 'dark' | null;
    const prefersDark = window?.matchMedia('(prefers-color-scheme: dark)').matches;
    const initial = stored || (prefersDark ? 'dark' : 'light');
    this.setTheme(initial, false);
  }

  setTheme(val: 'light' | 'dark', persist = true) {
    this.theme$.next(val);
    this.doc.documentElement.setAttribute('data-theme', val);
    if (persist) {
      localStorage.setItem('theme', val);
    }
  }
}
  1. 在 app.component.ts 中订阅并借助 Renderer2 做无刷新更新:
export class AppComponent implements OnInit {
  constructor(private theme: ThemeService, private renderer: Renderer2) {}

  ngOnInit() {
    this.theme.themeObs.subscribe(t => {
      this.renderer.setAttribute(document.documentElement, 'data-theme', t);
    });
  }
}
  1. 为了 SSR 安全,使用 APP_INITIALIZER 提前同步主题:
export function themeFactory(theme: ThemeService) {
  return () => theme.setTheme(localStorage.getItem('theme') as any || 'light', false);
}

@NgModule({
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: themeFactory,
      deps: [ThemeService],
      multi: true
    }
  ]
})
  1. 组件内使用变量:
.button {
  background: var(--brand-primary);
  color: var(--text-primary);
}
  1. 切换按钮模板:
<button (click)="theme.setTheme((theme.themeObs | async) === 'light' ? 'dark' : 'light')">
  {{ (theme.themeObs | async) === 'light' ? '🌙' : '☀️' }}
</button>

至此,不刷新页面、不重新请求样式文件,仅通过 data-theme 属性切换即可让所有 CSS 变量即时生效,且支持持久化、SSR、懒加载模块与第三方组件库无侵入。

拓展思考

  1. 多主题扩展:将变量抽成 JSON 文件,通过 HttpClient 动态加载,实现“运营后台一键换肤”;
  2. CSS 变量降级:针对国内低版本内核,使用 postcss-custom-properties 在构建时生成静态 fallback;
  3. 微前端场景:在 qiankun 子应用中把 ThemeService 提升为 single-spa prop,实现主子应用主题同步;
  4. 性能极限:利用 CSS containment 与 will-change 减少变量切换时的重绘面积;
  5. 安全合规:若项目涉政、金融,需把主题持久化从 localStorage 迁移到 HttpOnly Cookie,防止 XSS 窃取用户偏好。