gpt4 book ai didi

javascript - 更改主题并将其存储在本地存储中

转载 作者:太空宇宙 更新时间:2023-11-04 06:05:49 24 4
gpt4 key购买 nike

我有两个主题“深色”和“浅色”,我希望在单击复选框时更改主题。

这就是我改变主题的方式:

document.documentElement.setAttribute('data-theme', 'dark');

现在,这是有效的。但我希望将此更改保存在本地存储中,因此即使在重新加载页面后,主题仍保持不变。

这是我的代码:

checkBox.addEventListener('change', function () {
if(this.checked) {

document.documentElement.setAttribute('data-theme', 'dark');
localStorage.setItem( 'data-theme', 'dark');
}
else {
document.documentElement.setAttribute('data-theme', 'light');
localStorage.setItem('data-theme', 'light');
}
})

是我弄错了还是有什么地方不明白?

最佳答案

可以这样试试:

var checkBox = document.getElementById('cb');

var theme = window.localStorage.getItem('data-theme');
if(theme) document.documentElement.setAttribute('data-theme', theme);
checkBox.checked = theme == 'dark' ? true : false;

checkBox.addEventListener('change', function () {
if(this.checked){
document.documentElement.setAttribute('data-theme', 'dark');
window.localStorage.setItem('data-theme', 'dark');
} else {
document.documentElement.setAttribute('data-theme', 'light');
window.localStorage.setItem('data-theme', 'light');
}
});
<input id="cb" type="checkbox" />
<label for="cb">Checkbox</label>

关于javascript - 更改主题并将其存储在本地存储中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56871118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com