-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme.js
More file actions
51 lines (42 loc) · 1.67 KB
/
Copy paththeme.js
File metadata and controls
51 lines (42 loc) · 1.67 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
47
48
49
50
51
const STORAGE_KEY = 'grades-theme';
export function getInitialTheme() {
const storedTheme = localStorage.getItem(STORAGE_KEY);
if (storedTheme === 'light' || storedTheme === 'dark') return storedTheme;
return 'dark';
}
export function applyTheme(theme) {
const root = document.documentElement;
if (theme === 'light') {
root.setAttribute('data-theme', 'light');
} else {
root.removeAttribute('data-theme');
}
const toggleBtn = document.getElementById('themeToggleBtn');
const sunIcon = toggleBtn?.querySelector('.theme-icon-sun');
const moonIcon = toggleBtn?.querySelector('.theme-icon-moon');
if (sunIcon && moonIcon) {
const isLight = theme === 'light';
sunIcon.classList.toggle('hidden', !isLight);
moonIcon.classList.toggle('hidden', isLight);
}
if (toggleBtn) {
const nextThemeLabel = theme === 'light' ? '深色' : '淺色';
toggleBtn.setAttribute('aria-label', `切換至${nextThemeLabel}模式`);
toggleBtn.setAttribute('title', `切換至${nextThemeLabel}模式`);
toggleBtn.setAttribute('aria-pressed', theme === 'dark' ? 'true' : 'false');
}
document.dispatchEvent(new CustomEvent('themechange', {
detail: { theme }
}));
}
export function setupThemeToggle() {
const toggleBtn = document.getElementById('themeToggleBtn');
if (!toggleBtn) return;
let currentTheme = getInitialTheme();
applyTheme(currentTheme);
toggleBtn.addEventListener('click', () => {
currentTheme = currentTheme === 'light' ? 'dark' : 'light';
applyTheme(currentTheme);
localStorage.setItem(STORAGE_KEY, currentTheme);
});
}