如何在多个页面上设置光/黑模式?
我正在尝试使用LocalStorage来保持我的主题在页面上的更改上保持一致,但我似乎无法正常工作。
这就是我的HTML的样子:
<body onload="checkLightMode()">
<li><button class="mode-toggle"><i class="fas fa-sun fa-2x"></i></button></li>
JavaScript:
const button = document.querySelector
'.mode-toggle')
button.addEventListener('click', function () {
localStorage.setItem('light-mode', true)
if (localStorage.getItem('light-mode')) {
document.body.classList.toggle('light-mode')
document.querySelectorAll('.fa-sun').forEach(icon => icon.classList.toggle('fa-moon'))
} else {
document.body.classList.remove('light-mode')
localStorage.setItem('light-mode', false)
}
})
function checkLightMode() {
if (localStorage.getItem('light-mode')) {
body.classList.add('light-mode')
}
}
I am trying to use localStorage to keep my theme consistent over page changes but I can't seem to get it to work.
This is what my html looks like:
<body onload="checkLightMode()">
<li><button class="mode-toggle"><i class="fas fa-sun fa-2x"></i></button></li>
And the JavaScript:
const button = document.querySelector
'.mode-toggle')
button.addEventListener('click', function () {
localStorage.setItem('light-mode', true)
if (localStorage.getItem('light-mode')) {
document.body.classList.toggle('light-mode')
document.querySelectorAll('.fa-sun').forEach(icon => icon.classList.toggle('fa-moon'))
} else {
document.body.classList.remove('light-mode')
localStorage.setItem('light-mode', false)
}
})
function checkLightMode() {
if (localStorage.getItem('light-mode')) {
body.classList.add('light-mode')
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我能够使它上班!这就是窍门。它最终非常简单,我不需要on load功能。
I was able to get it to work! Here is what did the trick. It ended up being quite simple, and I didn't need the onload function.
我无法在沙盒代码段中使用本地存储,因此我使用可变的是相同的概念。
I can't use local storage in sandbox code snippet so I did it with variable, it should be the same concept.
我创建一个state.js文件,这将是第一个加载的模块。 (遵循角度方法)。
我放在所有全球变量。我认为很容易应付和满足您的需求。
使用此方法,您将不止一次创建此变量,
它停留在有组织的文件中,
而且很容易维护。
I create a state.js file, which will be the first module that loads. (Following angular methodology).
There I put all global variables. I think it's easy to handle and suits your needs.
With this method you would create this variable more than once,
It's stays in an organized file,
And it is easy to maintain.