我正在尝试使用localStorage在我的网站上保存黑暗模式首选项。我遇到的问题是当你切换到暗模式并点击刷新时,它会保持黑暗模式。但是,如果您切换到暗模式,然后返回到光模式,然后点击刷新,它会加载暗模式。
到目前为止,我陷入困境,但尚无法找到任何有用的资源。
这是我的小提琴以及下面的js脚本。
使用Javascript
$(document).ready(function(){
$('ul').click(function(){
$('ul').toggleClass('active')
let darkThemeEnabled = $('section').toggleClass('dark');
localStorage.setItem('dark-theme-enabled', darkThemeEnabled);
})
})
if (localStorage.getItem('dark-theme-enabled')) {
$('section').toggleClass('dark');
$('ul').toggleClass('active');
}
你需要设置一个布尔值到localStorage
:
$("section").toggleClass("dark");
let darkThemeEnabled = $("section").hasClass("dark");
localStorage.setItem("dark-theme-enabled", darkThemeEnabled);
还要改变你的获取方法:
if (localStorage.getItem('dark-theme-enabled')) {
$('section').addClass('dark');
$('ul').addClass('active');
}
这对我有用(我把我的黑暗模式放在我身上):
const body = document.querySelector('body');
const checkBox = document.getElementById('checkbox');
window.addEventListener('load', () => {
if (!localStorage.dark_mode)
localStorage.dark_mode = false;
else if (JSON.parse(localStorage.dark_mode) === true) {
body.classList.add('dark-mode');
checkbox.checked = true;
}
});
checkBox.addEventListener('click', (e) => {
body.classList.toggle('dark-mode');
if (body.classList.contains('dark-mode')) {
checkbox.checked = true;
localStorage.dark_mode = true;
}
else {
checkbox.checked = false;
localStorage.dark_mode = false;
}
});