mirror of
https://github.com/reonokiy/blog.nokiy.net.git
synced 2025-06-16 19:51:07 +02:00
fix: theme toggle error
This commit is contained in:
parent
60f42bd52a
commit
2f52b38100
2 changed files with 13 additions and 16 deletions
|
@ -1,14 +1,12 @@
|
|||
<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
|
||||
|
@ -20,18 +18,8 @@
|
|||
document.startViewTransition(switchTheme)
|
||||
}
|
||||
|
||||
// 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
|
||||
// Event listener
|
||||
themeToggle.addEventListener('click', toggleTheme)
|
||||
document.addEventListener('astro:after-swap', syncTheme)
|
||||
window.addEventListener('popstate', syncTheme)
|
||||
document.addEventListener('DOMContentLoaded', syncTheme)
|
||||
</script>
|
||||
|
||||
<button
|
||||
|
|
|
@ -95,10 +95,19 @@ const { cdn, commentURL = '', imageHostURL = '', customGoogleAnalyticsURL = '',
|
|||
|
||||
<!-- Theme Toggle -->
|
||||
<script is:inline define:vars={{ defaultMode: themeConfig.color.mode }}>
|
||||
const systemTheme = matchMedia('(prefers-color-scheme: dark)')
|
||||
const theme = localStorage.getItem('theme')
|
||||
?? (systemTheme.matches !== null ? (systemTheme.matches ? 'dark' : 'light') : defaultMode)
|
||||
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()
|
||||
document.documentElement.classList.toggle('dark', theme === 'dark')
|
||||
}
|
||||
updateTheme()
|
||||
document.addEventListener('astro:after-swap', updateTheme)
|
||||
</script>
|
||||
|
||||
<!-- Google Analytics -->
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue