当前位置:首页 > JavaScript

js实现暗黑模式

2026-02-02 20:53:49JavaScript

使用CSS变量实现暗黑模式

通过CSS变量定义主题颜色,JavaScript切换变量值实现暗黑/亮色模式切换。这种方法维护方便,只需修改少量CSS变量。

js实现暗黑模式

:root {
  --bg-color: #ffffff;
  --text-color: #333333;
}

[data-theme="dark"] {
  --bg-color: #1a1a1a;
  --text-color: #f0f0f0;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: background-color 0.3s, color 0.3s;
}
function toggleDarkMode() {
  const htmlElement = document.documentElement;
  const currentTheme = htmlElement.getAttribute('data-theme');

  if (currentTheme === 'dark') {
    htmlElement.removeAttribute('data-theme');
    localStorage.setItem('theme', 'light');
  } else {
    htmlElement.setAttribute('data-theme', 'dark');
    localStorage.setItem('theme', 'dark');
  }
}

// 初始化时读取本地存储的主题设置
function initializeTheme() {
  const savedTheme = localStorage.getItem('theme') || 'light';
  if (savedTheme === 'dark') {
    document.documentElement.setAttribute('data-theme', 'dark');
  }
}

initializeTheme();

使用class切换实现暗黑模式

通过添加/移除特定class来切换样式,适合简单项目或需要兼容旧浏览器的场景。

js实现暗黑模式

.light-mode {
  background-color: #ffffff;
  color: #333333;
}

.dark-mode {
  background-color: #1a1a1a;
  color: #f0f0f0;
}

body {
  transition: background-color 0.3s, color 0.3s;
}
function toggleDarkMode() {
  const body = document.body;

  if (body.classList.contains('dark-mode')) {
    body.classList.remove('dark-mode');
    body.classList.add('light-mode');
    localStorage.setItem('theme', 'light');
  } else {
    body.classList.remove('light-mode');
    body.classList.add('dark-mode');
    localStorage.setItem('theme', 'dark');
  }
}

// 初始化主题
function initializeTheme() {
  const savedTheme = localStorage.getItem('theme') || 'light';
  document.body.classList.add(savedTheme + '-mode');
}

initializeTheme();

跟随系统偏好设置

自动检测用户系统主题偏好,提供更无缝的体验。

// 检测系统主题偏好
function checkSystemPreference() {
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    return 'dark';
  }
  return 'light';
}

// 初始化主题时考虑系统偏好
function initializeTheme() {
  const savedTheme = localStorage.getItem('theme');
  const systemTheme = checkSystemPreference();
  const themeToApply = savedTheme || systemTheme;

  if (themeToApply === 'dark') {
    document.documentElement.setAttribute('data-theme', 'dark');
  }
}

// 监听系统主题变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
  if (localStorage.getItem('theme')) return; // 如果用户手动选择过主题,则忽略系统变化

  if (e.matches) {
    document.documentElement.setAttribute('data-theme', 'dark');
  } else {
    document.documentElement.removeAttribute('data-theme');
  }
});

initializeTheme();

完整实现示例

结合上述方法的完整实现,包含切换按钮和持久化存储。

<button id="theme-toggle">切换主题</button>
document.getElementById('theme-toggle').addEventListener('click', toggleDarkMode);

function toggleDarkMode() {
  const htmlElement = document.documentElement;
  const currentTheme = htmlElement.getAttribute('data-theme') || 'light';
  const newTheme = currentTheme === 'dark' ? 'light' : 'dark';

  htmlElement.setAttribute('data-theme', newTheme);
  localStorage.setItem('theme', newTheme);

  // 可选:更新按钮文本
  document.getElementById('theme-toggle').textContent = 
    newTheme === 'dark' ? '切换亮色模式' : '切换暗黑模式';
}

function initializeTheme() {
  const savedTheme = localStorage.getItem('theme');
  const systemTheme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches 
    ? 'dark' 
    : 'light';
  const themeToApply = savedTheme || systemTheme;

  if (themeToApply === 'dark') {
    document.documentElement.setAttribute('data-theme', 'dark');
    document.getElementById('theme-toggle').textContent = '切换亮色模式';
  }
}

initializeTheme();

注意事项

CSS过渡效果确保主题切换平滑,避免突兀变化 持久化存储使用localStorage,确保用户偏好被记住 系统主题检测提供开箱即用的体验 媒体查询监听确保实时响应系统主题变化 按钮状态更新提供清晰的用户反馈

标签: 模式js
分享给朋友:

相关文章

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callback) {…

js实现dh

js实现dh

JavaScript 实现 DH(Diffie-Hellman)密钥交换 Diffie-Hellman(DH)密钥交换是一种安全协议,允许双方在不安全的通信信道上建立一个共享密钥。以下是如何在 Jav…

js实现祖玛

js实现祖玛

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: const…

利用js实现

利用js实现

使用 JavaScript 实现 在 JavaScript 中,可以通过多种方式实现功能,具体取决于需求。以下是几种常见的方法: 方法一:使用原生 JavaScript // 示例代码 funct…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…

js实现下拉刷新

js实现下拉刷新

监听触摸事件 通过监听 touchstart、touchmove 和 touchend 事件来检测用户下拉手势。记录触摸起始位置和移动距离。 let startY = 0; let curr…