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

如何让prefers-color-scheme读取Chrome浏览器主题而非系统级(优先纯CSS)

解决方案

纯CSS方案

目前没有原生CSS媒体查询能直接读取Chrome浏览器级的主题设置,prefers-color-scheme本质是读取系统级的主题偏好,无法区分Chrome自行设置的主题与系统主题,因此纯CSS无法满足需求,需通过JavaScript实现。

JavaScript方案

普通网页可用的检测方法

Chrome的内置浅色/深色主题会影响原生控件的默认样式,我们可以通过创建隐藏的原生输入框,检测其背景色来判断当前Chrome主题:

// 检测Chrome当前主题
function detectChromeTheme() {
  const testInput = document.createElement('input');
  testInput.style.position = 'absolute';
  testInput.style.opacity = '0';
  document.body.appendChild(testInput);
  
  const computedStyle = window.getComputedStyle(testInput);
  const bgColor = computedStyle.backgroundColor;
  
  document.body.removeChild(testInput);
  
  // Chrome深色主题下输入框背景色为深灰(值随版本可能微调,需适配)
  if (bgColor === 'rgb(48, 48, 48)' || bgColor === '#303030') {
    return 'dark';
  } else {
    return 'light';
  }
}

// 给网页根元素设置主题标识
function applyTheme(theme) {
  document.documentElement.setAttribute('data-theme', theme);
}

// 初始检测并应用主题
applyTheme(detectChromeTheme());

// 监听主题变化(Chrome切换主题时会触发页面重绘,用定时检测保证实时性)
setInterval(() => {
  const currentTheme = detectChromeTheme();
  if (document.documentElement.getAttribute('data-theme') !== currentTheme) {
    applyTheme(currentTheme);
  }
}, 1000);

配合CSS使用

在CSS中根据data-theme属性定义主题样式:

[data-theme="light"] {
  --bg-color: #ffffff;
  --text-color: #000000;
}

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

body {
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: background-color 0.3s, color 0.3s;
}

注意事项

  • 检测用的颜色值可能随Chrome版本更新变化,需根据实际版本调整判断条件。
  • 定时检测的间隔可根据需求调整,平衡性能与实时性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 10:50:11