更改主题并将其存储在本地存储中 [英] Change theme and store it in local storage

查看:55
本文介绍了更改主题并将其存储在本地存储中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个主题:黑暗"和浅色",我希望在单击复选框时可以更改主题.

I have two themes "dark" and "light", and I want the theme to change when clicking the checkbox.

这是我更改主题的方式:

This is how I changed the theme:

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

现在,这正在起作用.但是我希望将此更改保存在本地存储中,因此,即使在重新加载页面后,主题也可以保持不变而不更改.

And now, this is working. But I want this change to be saved in local storage, thus even after reloading the page, the theme to stay as it is without changing.

这是我的代码:

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');
    }
})

我犯了一个错误还是有我不明白的地方?

Did I made a mistake or is there something I don't understand?

推荐答案

可以这样尝试:

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>

这篇关于更改主题并将其存储在本地存储中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆