-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme.js
More file actions
46 lines (40 loc) · 1.48 KB
/
Copy paththeme.js
File metadata and controls
46 lines (40 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
(() => {
const root = document.documentElement;
const toggle = document.querySelector(".theme-toggle");
const icon = toggle && toggle.querySelector(".theme-icon");
const label = toggle && toggle.querySelector(".theme-label");
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)");
if (!toggle || !icon || !label) return;
const updateToggle = () => {
const isDark = root.dataset.theme === "dark";
icon.textContent = isDark ? "☀️" : "🌙";
label.textContent = isDark ? "日间模式" : "夜间模式";
toggle.setAttribute("aria-label", isDark ? "切换到日间模式" : "切换到夜间模式");
toggle.setAttribute("aria-pressed", String(isDark));
};
toggle.addEventListener("click", () => {
const nextTheme = root.dataset.theme === "dark" ? "light" : "dark";
root.dataset.theme = nextTheme;
try {
localStorage.setItem("theme", nextTheme);
} catch (error) {
// 本地存储不可用时,切换仍对当前页面有效。
}
updateToggle();
});
const followSystemTheme = (event) => {
try {
if (localStorage.getItem("theme")) return;
} catch (error) {
// 无法读取本地存储时继续跟随系统主题。
}
root.dataset.theme = event.matches ? "dark" : "light";
updateToggle();
};
if (systemTheme.addEventListener) {
systemTheme.addEventListener("change", followSystemTheme);
} else {
systemTheme.addListener(followSystemTheme);
}
updateToggle();
})();