diff options
| author | muqiuhan <[email protected]> | 2025-03-13 09:18:34 +0000 |
|---|---|---|
| committer | muqiuhan <[email protected]> | 2025-03-13 09:18:34 +0000 |
| commit | 8fdca49e1d63db1075a23958ff23189818a49d6c (patch) | |
| tree | be90fc0db1afa1a273b8fb07659977fa5d903141 /js/theme-switch.js | |
| parent | c09bb17ff02d837b0be0b66b679eceb5bf7ec161 (diff) | |
| download | blog-8fdca49e1d63db1075a23958ff23189818a49d6c.tar.gz | |
deploy: 11fd5b5345c11055a7c18e9b2c0baa4d2787fe15
Diffstat (limited to 'js/theme-switch.js')
| -rw-r--r-- | js/theme-switch.js | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/js/theme-switch.js b/js/theme-switch.js new file mode 100644 index 00000000..4dddd304 --- /dev/null +++ b/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 |
