当前位置:首页 > JavaScript

js实现暗黑模式

2026-02-02 20:53:49JavaScript

使用CSS变量实现暗黑模式

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

: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来切换样式,适合简单项目或需要兼容旧浏览器的场景。

.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();

完整实现示例

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

js实现暗黑模式

<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手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…

js怎么实现异步

js怎么实现异步

异步实现方法 JavaScript中实现异步操作主要通过以下几种方式: Promise Promise是ES6引入的异步解决方案,用于处理异步操作的成功或失败状态。 const promise =…

js实现下拉菜单

js实现下拉菜单

使用HTML和CSS创建基础结构 HTML部分需要包含一个触发下拉的按钮和隐藏的下拉菜单内容: <div class="dropdown"> <button class="dr…

js实现搜索

js实现搜索

实现搜索功能的方法 在JavaScript中实现搜索功能可以通过多种方式完成,以下是几种常见的实现方法。 使用数组的filter方法 通过数组的filter方法可以筛选出符合条件的数据项。假设有一个…

js进度条实现

js进度条实现

使用HTML和CSS创建基础结构 在HTML中创建一个容器元素用于显示进度条,通常使用<div>元素。CSS用于设置进度条的样式,包括宽度、高度、颜色和圆角等属性。 <div cl…

js实现定位

js实现定位

使用Geolocation API获取当前位置 在JavaScript中,可以通过浏览器内置的Geolocation API获取用户的地理位置信息。该API需要用户授权才能访问位置数据。 if (n…