我正在尝试制作一个暗模式切换按钮,可以在单击时在暗模式和亮模式之间切换,用户首选项也使用 localStorage
存储。用户应手动按下按钮以切换到其他模式。如果用户选择的是深色模式,则每个页面都将处于深色模式,并且不会在刷新时转为浅色模式。到目前为止一切看起来都很好,但真正的问题在于加载时间。一个页面的加载时间将近 1 秒,在此期间,即使用户选择了深色模式,页面也似乎处于浅色模式。我不希望发生这种情况。如果用户的选择是黑暗的,我想在黑暗模式下加载时间部分。
这是我当前的代码:
<script>
const body = document.querySelector('body');
function toggleDark() {
if (body.classList.contains('dark')) {
body.classList.remove('dark');
localStorage.setItem("theme", "light");
} else {
body.classList.add('dark');
localStorage.setItem("theme", "dark");
}
}
if (localStorage.getItem("theme") === "dark") {
body.classList.add('dark');
}
</script>
<style>
body {background-color: #ffffff}
body.dark {background-color: #000000; color: #ffffff}
</style>
<button class="dark-mode" id="btn-id" onclick="toggleDark()"></button>
最佳答案
另一种选择是在 <head>
中加载脚本元素,并在 html
上切换类元素
为此,您使用 document.documentElement.classList
因为那是 HTML
元素
然后将您的 CSS 更改为
html.dark body {}
等等 .. HTML 上的类选择器
html body {background-color: #ffffff}
html.dark body {background-color: #000000; color: #ffffff}
<script>
const body = document.querySelector('body');
function toggleDark() {
if (document.documentElement.classList.contains('dark')) {
document.documentElement.classList.remove('dark');
//localStorage.setItem("theme", "light");
} else {
document.documentElement.classList.add('dark');
//localStorage.setItem("theme", "dark");
}
}
//if (localStorage.getItem("theme") === "dark") {
document.documentElement.classList.add('dark');
//}
</script>
<button class="dark-mode" id="btn-id" onclick="toggleDark()">DARK</button>
Due to restrictions,
localStorage
is unavailable on stack overflow - uncomment those lines to see it work
或者 - 参见 https://jsfiddle.net/e9zg2p4c/
关于javascript - 暗模式在加载期间不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64167519/