bug fix: DOMContentLoaded

This commit is contained in:
Junyi Hou 2024-03-13 16:14:18 +08:00
parent e61809d59a
commit 4cba618ce1

View File

@ -1,16 +1,16 @@
{{ $style := "light-without-switcher" }}
{{ if and (isset site.Params "style") (ne site.Params.style "") }}
{{ $style = site.Params.style | lower }}
{{ $style = site.Params.style | lower }}
{{ end }}
{{ if not (in (slice "light-without-switcher" "dark-without-switcher") $style) }}
{{ if ne "auto-without-switcher" $style }}
<div class="theme-switcher">
{{ if ne "auto-without-switcher" $style }}
<div class="theme-switcher">
{{ partial "font-awesome.html" (dict "iconName" "theme-light" "custom" false) }}
</div>
{{ end }}
</div>
{{ end }}
<script>
<script>
const STORAGE_KEY = 'user-color-scheme'
const defaultTheme = {{ $style }}
@ -23,15 +23,15 @@
document.documentElement.setAttribute('data-theme', currentTheme)
}
document.addEventListener('DOMContentLoaded', function() {
document.addEventListener('DOMContentLoaded', function () {
switchButton = document.querySelector('.theme-switcher')
currentTheme = detectCurrentScheme()
if (currentTheme == 'dark') {
document.documentElement.setAttribute('data-theme', 'dark')
}
if (currentTheme == 'auto') {
if (currentTheme === 'auto') {
autoChangeScheme(autoDefinedScheme);
autoDefinedScheme.addListener(autoChangeScheme);
} else {
document.documentElement.setAttribute('data-theme', currentTheme)
}
if (switchButton) {
@ -48,32 +48,18 @@
if (defaultTheme) {
return defaultTheme
}
if (!window.matchMedia) {
return 'light'
}
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark'
}
return 'light'
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function switchTheme(e) {
if (currentTheme == 'dark') {
if (localStorage !== null)
localStorage.setItem(STORAGE_KEY, 'light')
document.documentElement.setAttribute('data-theme', 'light')
currentTheme = 'light'
} else {
if (localStorage !== null)
localStorage.setItem(STORAGE_KEY, 'dark')
document.documentElement.setAttribute('data-theme', 'dark')
currentTheme = 'dark'
}
currentTheme = (currentTheme === 'dark') ? 'light' : 'dark';
if (localStorage) localStorage.setItem(STORAGE_KEY, currentTheme);
document.documentElement.setAttribute('data-theme', currentTheme);
}
function showContent() {
document.body.style.visibility = 'visible';
document.body.style.opacity = 1;
}
</script>
</script>
{{ end }}