浅色/深色主题切换,是一个常见的功能。以 ESLint(https://eslint.org/)官网为例,底部的三个按钮 Light、System、Dark 会分别切换到浅色、系统偏好和深色。
如果你想实现这个功能,只需掌握 CSS 变量和媒体查询这两个基础知识即可。
CSS 变量,也叫 CSS 自定义属性,是现代 CSS 自带的原生变量,支持度良好。CSS 变量名使用双短横线(--)开头,获取 CSS 变量值时使用 var() 函数。
CSS 变量是有作用域的。在某个选择符上定义的变量,它的所有子元素都能访问到,但是它的父元素或兄弟元素访问不到。因此,全局变量一般在顶级标签 html 中声明。另外,html 还有一个别名,即 :root 伪类。
为了实现主题切换,需要准备两套 CSS 变量值,一套是白底黑字,一套是黑底白字。两者通过 html 标签的 data-theme 属性进行区分。
之所以使用 data-theme 属性,因为可以通过元素的 dataset 属性,很方便的动态修改。
现在可以添加一段测试代码,验证主题切换是否生效。
如果用户的主题选择跟随系统,那么我们需要获知当前系统的偏好设置。
偏好设置可以通过媒体查询获得,具体到 JS 代码,可以使用 window.matchMedia() 函数获取。
matchMedia() 函数的返回值是一个 MediaQueryList 对象。它的 matches 布尔值属性表示是否匹配查询字符串的内容。它还可以通过监听 change 事件,获取实时的系统偏好。
matchMedia() 可以查询的内容很多,比如屏幕尺寸、设备像素比等。具体到主题颜色,输入的查询字符串是 "(prefers-color-scheme: dark)" 或 "(prefers-color-scheme: light)"。
除此之外,还有一些交互细节,比如使用 localStorage 将用户的选择存储到本地等。
整体代码大致如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dark Mode</title>
<style>
:root {
--bg-color: #111;
--text-color: #fff;
}
:root[data-theme="light"] {
--bg-color: #fff;
--text-color: #111;
}
body {
background: var(--bg-color);
color: var(--text-color);
}
</style>
</head>
<body>
<h1>Title</h1>
<p>Hello world, foobar!</p>
<fieldset id="theme-switch">
<legend>选择主题</legend>
<label> <input type="radio" name="theme" value="light" /> 浅色 </label>
<label> <input type="radio" name="theme" value="system" /> 系统 </label>
<label> <input type="radio" name="theme" value="dark" /> 深色 </label>
</fieldset>
<script>
// 监听主题选择的变化
document.querySelector("#theme-switch").addEventListener("change", (e) => {
setTheme(e.target.value);
});
// 初始化主题
initTheme();
// 修改主题颜色
function setTheme(theme) {
localStorage.setItem("theme", theme);
// 读取系统偏好
if (theme === "system") {
const preferDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
document.documentElement.dataset.theme = preferDark ? "dark" : "light";
} else {
document.documentElement.dataset.theme = theme;
}
}
function initTheme() {
const savedTheme = localStorage.getItem("theme");
if (savedTheme) {
setTheme(savedTheme);
}
// 更新控件状态
document.querySelector(`input[type="radio"][value="${savedTheme}"]`).checked = true;
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
const current = localStorage.getItem("theme");
if (current === "system" || !current) {
setTheme("system");
}
});
}
</script>
</body>
</html>
最后,如果你想在浏览器调试系统偏好的主题色,可以使用开发者工具的【绘制】标签(或者 Rendering)。
这个标签默认看不到,需要手动将其添加到开发者工具栏。
完