[英]How do I switch my theme based on data from local storage
My theme settings always revert to the default theme on page refresh despite reading the theme settings from local storage 尽管从本地存储中读取主题设置,但我的主题设置始终会恢复为页面刷新时的默认主题
Here is my code for the theme implementation: 这是我的主题实现代码:
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');
});
I've checked the localStorage and the theme values are stored 我检查了localStorage并存储了主题值
In your Initial class instead of setting it to empty, set the local storage to the default theme and read the theme value from local storage in your initial class. 在Initial类中,不要将其设置为空,将本地存储设置为默认主题,并从初始类的本地存储中读取主题值。 So that on page reload also you will be reading the theme from the local storage and it will be set already with the custom theme.
因此,在页面重新加载时,您将从本地存储中读取主题,并且将使用自定义主题进行设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.