Files
qihuo/static/js/theme.js
T

37 lines
1.2 KiB
JavaScript

(function () {
var KEY = 'qihuo-theme';
function apply(theme) {
document.documentElement.setAttribute('data-theme', theme);
try {
localStorage.setItem(KEY, theme);
} catch (e) { /* ignore */ }
var btn = document.getElementById('theme-toggle');
if (btn) {
btn.setAttribute('data-active', theme);
btn.setAttribute('aria-label', theme === 'light' ? '切换到深色' : '切换到浅色');
}
}
var saved = null;
try {
saved = localStorage.getItem(KEY);
} catch (e) { /* ignore */ }
if (saved === 'light' || saved === 'dark') {
apply(saved);
} else {
var prefersLight = window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches;
apply(prefersLight ? 'light' : 'dark');
}
document.addEventListener('DOMContentLoaded', function () {
var btn = document.getElementById('theme-toggle');
if (!btn) return;
btn.addEventListener('click', function () {
var cur = document.documentElement.getAttribute('data-theme') || 'dark';
apply(cur === 'dark' ? 'light' : 'dark');
});
});
})();