fix: theme toggle error

This commit is contained in:
radishzzz 2025-01-23 23:33:32 +00:00
parent 2f52b38100
commit 00149b251b
2 changed files with 41 additions and 12 deletions

View file

@ -95,19 +95,32 @@ const { cdn, commentURL = '', imageHostURL = '', customGoogleAnalyticsURL = '',
<!-- Theme Toggle -->
<script is:inline define:vars={{ defaultMode: themeConfig.color.mode }}>
function getTheme() {
const storedTheme = localStorage.getItem('theme')
if (storedTheme)
return storedTheme
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
return systemTheme ? 'dark' : defaultMode
}
function updateTheme() {
const theme = localStorage.getItem('theme') || getTheme()
function initTheme() {
const theme = (() => {
// 1. 检查 localStorage
if (typeof localStorage !== 'undefined' && localStorage.getItem('theme')) {
return localStorage.getItem('theme')
}
// 2. 检查系统主题
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark'
}
// 3. 使用默认主题
return defaultMode
})()
document.documentElement.classList.toggle('dark', theme === 'dark')
}
updateTheme()
document.addEventListener('astro:after-swap', updateTheme)
// 立即执行初始化
initTheme()
// 监听系统主题变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
if (!localStorage.getItem('theme')) { // 只在用户未手动设置主题时响应
document.documentElement.classList.toggle('dark', e.matches)
}
})
</script>
<!-- Google Analytics -->