当前位置:首页 > 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实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

js实现倒计时

js实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时功能可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是几种常见的实现方式: 使用 setInterv…

js实现验证码

js实现验证码

实现验证码的JavaScript方法 生成随机验证码 使用Math.random()生成随机字符串,结合数字和字母: function generateCaptcha() { const ch…

jquery.js

jquery.js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,用于简化 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它的设计宗旨是“Write Less, Do Mor…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的HT…