mirror of
https://github.com/reonokiy/blog.nokiy.net.git
synced 2025-06-17 12:01:33 +02:00
fix: theme toggle error
This commit is contained in:
parent
2f52b38100
commit
00149b251b
2 changed files with 41 additions and 12 deletions
|
@ -1,12 +1,14 @@
|
|||
<script>
|
||||
// Initialize theme toggle button
|
||||
const themeToggle = document.querySelector('button[aria-pressed]') as HTMLButtonElement
|
||||
themeToggle.setAttribute('aria-pressed', String(document.documentElement.classList.contains('dark')))
|
||||
|
||||
// Core theme switching logic
|
||||
function switchTheme() {
|
||||
const isDark = document.documentElement.classList.toggle('dark')
|
||||
themeToggle.setAttribute('aria-pressed', String(isDark))
|
||||
localStorage.setItem('theme', isDark ? 'dark' : 'light')
|
||||
document.dispatchEvent(new Event('theme-changed'))
|
||||
}
|
||||
|
||||
// Handle theme toggle with view transitions API
|
||||
|
@ -18,8 +20,22 @@
|
|||
document.startViewTransition(switchTheme)
|
||||
}
|
||||
|
||||
// Event listener
|
||||
// Sync theme state
|
||||
function syncTheme() {
|
||||
const theme = localStorage.getItem('theme')
|
||||
document.documentElement.classList.toggle('dark', theme === 'dark')
|
||||
themeToggle.setAttribute('aria-pressed', String(theme === 'dark'))
|
||||
}
|
||||
|
||||
// Event listeners
|
||||
themeToggle.addEventListener('click', toggleTheme)
|
||||
document.addEventListener('astro:after-swap', syncTheme)
|
||||
window.addEventListener('popstate', syncTheme)
|
||||
window.addEventListener('pageshow', (event) => {
|
||||
if (event.persisted) {
|
||||
syncTheme()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<button
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue