You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中实现Tailwind暗黑模式主题切换?

基于Tailwind实现Angular暗黑模式切换方案

步骤1:配置Tailwind暗黑模式策略

修改你的tailwind.config.js文件,开启手动类名切换暗黑模式,同时扩展自定义主题色,和你原有变量对齐:

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: 'class', // 核心配置:通过类名切换暗黑模式
  content: [
    "./src/**/*.{html,ts}",
  ],
  theme: {
    extend: {
      colors: {
        primary: 'var(--primary)',
        'secondary-bg': 'var(--secondary-bg)',
        theme: 'var(--theme)',
        'header-color': 'var(--header-color)',
        'route-link-active': 'var(--route-link-active)',
        'link-color': 'var(--link-color)',
        'border-color': 'var(--border-color)',
      }
    },
  },
  plugins: [],
}

步骤2:保留原有全局主题变量

你之前写的.theme-light和.theme-dark的变量配置直接复制到全局src/styles.css中即可,无需修改:

/* src/styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

.theme-light {
  --primary: #2577c1;
  --secondary-bg: #fff;
  --theme: #fff;
  --header-color: rgb(194, 63, 226);
  --route-link-active: #fff;
  --link-color: rgb(85, 80, 80);
  --border-color: rgb(85, 80, 80);
}
.theme-dark {
  --primary: rgb(255, 80, 11);
  --secondary-bg: #424242;
  --theme: #424242;
  --header-color: var(--theme);
  --route-link-active: rgb(255, 80, 11);
  --link-color: #fff;
  --border-color: rgb(28, 214, 28);
}

步骤3:修改App组件逻辑,操作body类名

通过Angular提供的DOCUMENT令牌注入全局document对象,实现给body动态添加/移除主题类:

import { Component, Inject, OnInit } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  isDarkEnable = false;
  presentTheme$ = new BehaviorSubject<string>('theme-light');

  // 注入document对象
  constructor(@Inject(DOCUMENT) private document: Document) {}

  ngOnInit() {
    const savedTheme = localStorage.getItem('theme');
    const initTheme = savedTheme || 'theme-light';
    this.presentTheme$.next(initTheme);
    // 初始化时给body加主题类
    this.document.body.classList.add(initTheme);
    this.isDarkEnable = initTheme === 'theme-dark';
  }

  changeTheme() {
    const oldTheme = this.presentTheme$.value;
    const newTheme = oldTheme === 'theme-light' ? 'theme-dark' : 'theme-light';
    // 替换body上的主题类
    this.document.body.classList.replace(oldTheme, newTheme);
    // 更新状态和本地存储
    this.presentTheme$.next(newTheme);
    localStorage.setItem('theme', newTheme);
    this.isDarkEnable = !this.isDarkEnable;
  }
}

步骤4:修改App组件模板

移除原来外层div的class绑定,因为主题类已经绑定到body上,其他逻辑不变:

<header>
  <app-header>
    <a *ngIf="isDarkEnable" (click)="changeTheme()" mode-button style="font-size:30px">LIGHT</a>
    <a *ngIf="!isDarkEnable" (click)="changeTheme()" mode-button style="font-size:30px">DARK</a>
  </app-header>
</header>

<main>
  <router-outlet></router-outlet>
</main>

后续使用说明

之后你在所有组件的模板里,直接用Tailwind的类名即可,比如背景色用bg-secondary-bg,文字颜色用text-link-color,需要暗黑模式特殊样式的话加dark:前缀就可以生效。

内容的提问来源于stack exchange,提问作者Rahiyan Safz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:21:00