fix: theme toggle fallback animation flash issue (final)

This commit is contained in:
radishzzz 2025-01-24 00:30:39 +00:00
parent 00149b251b
commit d4e5fda5d1
4 changed files with 44 additions and 45 deletions

View file

@ -5,6 +5,7 @@
// Core theme switching logic
function switchTheme() {
document.body.removeAttribute('data-restore-theme')
const isDark = document.documentElement.classList.toggle('dark')
themeToggle.setAttribute('aria-pressed', String(isDark))
localStorage.setItem('theme', isDark ? 'dark' : 'light')
@ -22,9 +23,13 @@
// Sync theme state
function syncTheme() {
document.body.setAttribute('data-restore-theme', 'true')
const theme = localStorage.getItem('theme')
document.documentElement.classList.toggle('dark', theme === 'dark')
themeToggle.setAttribute('aria-pressed', String(theme === 'dark'))
requestAnimationFrame(() => {
document.body.removeAttribute('data-restore-theme')
})
}
// Event listeners

View file

@ -97,27 +97,21 @@ const { cdn, commentURL = '', imageHostURL = '', customGoogleAnalyticsURL = '',
<script is:inline define:vars={{ defaultMode: themeConfig.color.mode }}>
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')
}
// 立即执行初始化
initTheme()
// 监听系统主题变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
if (!localStorage.getItem('theme')) { // 只在用户未手动设置主题时响应
if (!localStorage.getItem('theme')) {
document.documentElement.classList.toggle('dark', e.matches)
}
})

View file

@ -64,7 +64,7 @@ animation: none;
z-index: -1;
}
@supports not (view-transition-name: none) {
body {
body:not([data-restore-theme]) {
--at-apply: 'transition-all duration-500 ease-in-out';
}
}

View file

@ -12,9 +12,9 @@
}
.scrollbar-light {
--os-handle-bg: #D1C6BE;
--os-handle-bg-hover: #C1B6AF;
--os-handle-bg-active: #C1B6AF;
--os-handle-bg: #C9C4C1;
--os-handle-bg-hover: #B8B3B0;
--os-handle-bg-active: #B8B3B0;
}
.scrollbar-dark {