我试图使用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')
}
}发布于 2022-07-01 00:49:05
我让它开始工作了!这就是诀窍所在。结果很简单,我不需要onload函数。
const buttons = document.querySelectorAll('.mode-toggle')
buttons.forEach(button => {
button.addEventListener('click', function () {
document.body.classList.toggle('light-mode')
document.querySelectorAll('.fa-sun').forEach(icon => icon.classList.toggle('fa-moon'))
if (document.body.classList.contains('light-mode')) {
localStorage.setItem('lightMode', 'enabled')
} else {
localStorage.setItem('lightMode', 'disabled')
}
})
})
if (localStorage.getItem('lightMode') === 'enabled') {
document.body.classList.add('light-mode')
document.querySelectorAll('.fa-sun').forEach(icon => icon.classList.add('fa-moon'))
}发布于 2022-06-30 21:20:10
我不能在沙箱代码片段中使用本地存储,所以我使用了变量,它应该是相同的概念。
const button = document.querySelector('.mode-toggle')
var isTrueSet = (value) => value === 'true';
let lightMode = false;
button.addEventListener('click', function () {
const v = localStorage.getItem('light-mode');
if (!lightMode) { // change to (!v && !isTrueSet(v))
document.body.classList.add('light-mode')
lightMode = true
} else {
lightMode = false
document.body.classList.remove('light-mode')
}
})
function checkLightMode() {
const v = localStorage.getItem('light-mode');
if (lightMode) { // (!v && !isTrueSet(v))
body.classList.add('light-mode')
}
}body {
background-color: #000;
width: 100%;
height: 100%;
}
.light-mode {
background-color: #fff;
}<div id="one" onload="checkLightMode()">
<li><button class="mode-toggle">mode</button></li>
</div>
发布于 2022-06-30 21:28:24
我创建了一个state.js文件,这将是加载的第一个模块。(采用角度方法)。
在这里,我把所有的全局变量。我认为它很容易处理,并适合你的需要。
let lightMode = false;const button = document.querySelector('.mode-toggle')
button.addEventListener('click', function () {
if (!lightMode) {
document.body.classList.add('light-mode')
lightMode = true
} else {
lightMode = false
document.body.classList.remove('light-mode')
}
})
function checkLightMode() {
if (lightMode) {
body.classList.add('light-mode')
}
}使用此方法,您将不止一次地创建这个变量,它停留在一个有组织的文件中,并且易于维护。
https://stackoverflow.com/questions/72822021
复制相似问题