summaryrefslogtreecommitdiff
path: root/themes/theme/source/js/theme-switch.js
diff options
context:
space:
mode:
authorsomhairle <[email protected]>2026-04-21 20:40:27 +0800
committerSomhairle H. Marisol <[email protected]>2026-05-24 17:24:57 +0800
commitad8f9f55ea79a4d587aecc69698808da82de3d62 (patch)
treed25c0db712e6f015d850627ff957edea44c64f94 /themes/theme/source/js/theme-switch.js
downloadblog-ad8f9f55ea79a4d587aecc69698808da82de3d62.tar.gz
二〇二六年四月二十一日
Diffstat (limited to 'themes/theme/source/js/theme-switch.js')
-rw-r--r--themes/theme/source/js/theme-switch.js31
1 files changed, 31 insertions, 0 deletions
diff --git a/themes/theme/source/js/theme-switch.js b/themes/theme/source/js/theme-switch.js
new file mode 100644
index 00000000..4dddd304
--- /dev/null
+++ b/themes/theme/source/js/theme-switch.js
@@ -0,0 +1,31 @@
+document.addEventListener('DOMContentLoaded', () => {
+ const themeSwitch = document.getElementById('theme-switch-btn');
+ const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)');
+
+ // 检查本地存储中的主题设置
+ const currentTheme = localStorage.getItem('theme');
+ if (currentTheme === 'dark') {
+ document.body.classList.add('dark-theme');
+ themeSwitch.querySelector('i').classList.replace('icon-moon', 'icon-sun');
+ } else if (currentTheme === 'light') {
+ document.body.classList.remove('dark-theme');
+ } else if (prefersDarkScheme.matches) {
+ document.body.classList.add('dark-theme');
+ themeSwitch.querySelector('i').classList.replace('icon-moon', 'icon-sun');
+ }
+
+ // 切换主题
+ themeSwitch.addEventListener('click', (e) => {
+ e.preventDefault();
+
+ if (document.body.classList.contains('dark-theme')) {
+ document.body.classList.remove('dark-theme');
+ localStorage.setItem('theme', 'light');
+ themeSwitch.querySelector('i').classList.replace('icon-sun', 'icon-moon');
+ } else {
+ document.body.classList.add('dark-theme');
+ localStorage.setItem('theme', 'dark');
+ themeSwitch.querySelector('i').classList.replace('icon-moon', 'icon-sun');
+ }
+ });
+}); \ No newline at end of file