【问题标题】:How do I switch my theme based on data from local storage如何根据本地存储中的数据切换主题
【发布时间】:2019-05-30 00:18:43
【问题描述】:

尽管从本地存储读取了主题设置,但我的主题设置总是在页面刷新时恢复为默认主题

这是我的主题实现代码:

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 并存储了主题值

【问题讨论】:

  • 什么是初始类?您还需要根据值在页面加载时设置类。
  • 初始类为空字符串
  • 您需要使用默认主题初始化本地存储变量。在您的 Initial 类中,从本地存储中读取主题。

标签: javascript css local-storage


【解决方案1】:

在初始类中,不要将其设置为空,而是将本地存储设置为默认主题,并从初始类的本地存储中读取主题值。因此,在页面重新加载时,您也将从本地存储中读取主题,并且已经使用自定义主题进行了设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 2018-02-04
    相关资源
    最近更新 更多