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

如何为简易笔记应用添加可自定义的明暗主题切换功能?

实现笔记应用主题切换功能的具体方法

1. 用CSS自定义属性统一管理配色

把所有配色定义成CSS变量,切换主题时只需要替换变量值,不用逐个修改元素样式:

/* 浅色主题(默认) */
:root {
  --bg-color: #ffffff;
  --text-color: #1a1a1a;
  --border-color: #e0e0e0;
  --note-bg: #f9f9f9;
}

/* 深色主题 */
body.dark {
  --bg-color: #1a1a1a;
  --text-color: #ffffff;
  --border-color: #333333;
  --note-bg: #2d2d2d;
}

/* 将变量应用到实际元素 */
body {
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: background-color 0.3s, color 0.3s; /* 平滑过渡提升体验 */
}

.note-item {
  background-color: var(--note-bg);
  border: 1px solid var(--border-color);
  padding: 1rem;
  margin-bottom: 1rem;
}

2. 添加主题切换按钮

在页面的导航栏或设置区域加个简单按钮:

<button id="theme-switcher">切换到深色</button>

用JS处理点击事件,切换body上的主题类:

const themeBtn = document.getElementById('theme-switcher');

themeBtn.addEventListener('click', () => {
  const isDark = document.body.classList.toggle('dark');
  // 更新按钮文字提示
  themeBtn.textContent = isDark ? '切换到浅色' : '切换到深色';
});

3. 用本地存储记住用户选择

避免刷新页面后主题重置,把用户选择存在localStorage里:

const themeBtn = document.getElementById('theme-switcher');

// 页面加载时初始化主题
function initTheme() {
  // 优先取用户保存的设置,无设置则跟随系统偏好
  const savedTheme = localStorage.getItem('app-theme');
  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

  if (savedTheme === 'dark' || (!savedTheme && prefersDark)) {
    document.body.classList.add('dark');
    themeBtn.textContent = '切换到浅色';
  } else {
    themeBtn.textContent = '切换到深色';
  }
}

// 切换主题并保存设置
function toggleTheme() {
  const isDark = document.body.classList.toggle('dark');
  localStorage.setItem('app-theme', isDark ? 'dark' : 'light');
  themeBtn.textContent = isDark ? '切换到浅色' : '切换到深色';
}

// 绑定事件+初始化
document.addEventListener('DOMContentLoaded', initTheme);
themeBtn.addEventListener('click', toggleTheme);

4. 适配系统主题变化(可选)

如果用户未手动切换过主题,让应用自动跟随系统的深色/浅色模式:

// 监听系统主题偏好变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
  const savedTheme = localStorage.getItem('app-theme');
  // 仅当用户无手动设置时跟随系统
  if (!savedTheme) {
    if (e.matches) {
      document.body.classList.add('dark');
      themeBtn.textContent = '切换到浅色';
    } else {
      document.body.classList.remove('dark');
      themeBtn.textContent = '切换到深色';
    }
  }
});

额外小技巧

  • 可以把按钮换成太阳/月亮图标(用SVG或图标库),比文字更直观
  • 后续要加更多主题(比如复古棕、蓝色调),只需新增对应CSS类,修改切换逻辑即可
  • 检查所有组件样式都使用CSS变量,避免硬编码颜色导致主题切换不彻底

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:12:37