即使从本地存储中读取主题设置,我的主题设置也总是在页面刷新时恢复为默认主题
这是我实现主题的代码:
green.addEventListener('click', () => {
if (localStorage.getItem('theme') != 'green') {
localStorage.setItem('theme', 'green');
}
main.classList.add(localStorage.getItem('theme'));
});
yellow.addEventListener('click', () => {
if (localStorage.getItem('theme') !== 'yellow') {
localStorage.setItem('theme', 'yellow');
}
main.className = localStorage.getItem('theme');
});
purple.addEventListener('click', () => {
if (localStorage.getItem('theme') !== '') {
localStorage.setItem('theme', '');
}
main.className = localStorage.getItem('theme');
});
我已经检查了localStorage并存储了主题值
答案 0 :(得分:0)
在初始类中,而不是将其设置为空,而是将本地存储设置为默认主题,然后从初始类中的本地存储中读取主题值。这样一来,在重新加载页面时,您还将从本地存储中读取主题,并且已经使用自定义主题对其进行了设置。