1
0
Fork 0

fix dark mode

This commit is contained in:
nanxiaobei 2021-08-24 20:35:04 +08:00
parent 6dd2030dfe
commit 13431dae52
2 changed files with 15 additions and 24 deletions

View file

@ -202,7 +202,7 @@ img {
white-space: nowrap; white-space: nowrap;
} }
.btn-theme { .btn-dark {
width: 3rem; width: 3rem;
margin-left: 2rem; margin-left: 2rem;
cursor: pointer; cursor: pointer;
@ -210,7 +210,7 @@ img {
transition: background-position 0.4s steps(6); transition: background-position 0.4s steps(6);
} }
.dark .btn-theme { .dark .btn-dark {
background-position: right; background-position: right;
} }

View file

@ -1,39 +1,30 @@
<header class="header"> <header class="header">
{{ if .IsHome }} {{ if .IsHome }}
<h1 class="logo"> <h1 class="logo">
<a class="site-name" href="{{ `` | absURL }}">{{ site.Title }}</a><a class="btn-theme"></a> <a class="site-name" href="{{ `` | absURL }}">{{ site.Title }}</a><a class="btn-dark"></a>
</h1> </h1>
{{ else }} {{ else }}
<p class="logo"> <p class="logo">
<a class="site-name" href="{{ `` | absURL }}">{{ site.Title }}</a><a class="btn-theme"></a> <a class="site-name" href="{{ `` | absURL }}">{{ site.Title }}</a><a class="btn-dark"></a>
</p> </p>
{{ end }} {{ end }}
<script> <script>
let bodyClass = document.body.classList; let bodyClx = document.body.classList;
let buttonDark = document.querySelector('.btn-theme'); let btnDark = document.querySelector('.btn-dark');
let schemeDark = window.matchMedia('(prefers-color-scheme: dark)'); let sysDark = window.matchMedia('(prefers-color-scheme: dark)');
let darkVal = localStorage.getItem('dark');
let setDark = () => { let setDark = (isDark) => {
bodyClass.add('dark'); bodyClx[isDark ? 'add' : 'remove']('dark');
localStorage.setItem('dark', 'true'); localStorage.setItem('dark', isDark ? 'yes' : 'no');
};
let setLight = () => {
bodyClass.remove('dark');
localStorage.removeItem('dark');
}; };
if (schemeDark.matches || localStorage.getItem('dark')) setDark(); setDark(darkVal ? darkVal === 'yes' : sysDark.matches);
requestAnimationFrame(() => { requestAnimationFrame(() => bodyClx.remove('not-ready'));
bodyClass.remove('not-ready');
});
buttonDark.addEventListener('click', () => { btnDark.addEventListener('click', () => setDark(!bodyClx.contains('dark')));
bodyClass.contains('dark') ? setLight() : setDark(); sysDark.addEventListener('change', (event) => setDark(event.matches));
});
schemeDark.addEventListener('change', (event) => {
event.matches ? setDark() : setLight();
});
</script> </script>
{{ $url := .RelPermalink }}<!----> {{ $url := .RelPermalink }}<!---->