【问题标题】:Set color theme with localStorage使用 localStorage 设置颜色主题
【发布时间】:2021-09-11 22:56:29
【问题描述】:

我在我的网站上设置了一个颜色主题系统。当你点击一个按钮时,一个类被添加到<html> 并且其对应的主题生效。但是,当我第一次加载我的网站时(我使用隐身模式来模拟这一点),所有主题都不起作用。我想重写我的代码块,基本上说,“当 localStorage 中没有任何内容时,加载'theme-dark-blue'。”

这是我的代码:

  // function to set a given theme/color-scheme
  function setTheme(themeName) {
    localStorage.setItem('theme', themeName);
    document.documentElement.className = themeName;
  }

  // Immediately invoked function to set the theme on initial load
  (function () {
    if (localStorage.getItem('theme') === 'theme-dark-blue') {
      setTheme('theme-dark-blue');
    }
  })();

目前为止的其他主题是“theme-light-blue”和“theme-dark-green”。我正在考虑尝试将其表述为“如果<html> 没有课程,请设置'theme-dark-blue'”

【问题讨论】:

  • 那为什么不直接这样做:""当localStorage 中没有任何内容时,加载'theme-dark-blue'。"" ? if(localStorage.getItem('theme') === null)...
  • @EmrysMayell Doe 以下答案解决了您的问题吗?

标签: javascript local-storage


【解决方案1】:
  function setTheme(themeName) {
    localStorage.setItem('theme', themeName);
    document.documentElement.className = themeName;
  }

  // Immediately invoked function to set the theme on initial load
  (function () {
    if (localStorage.getItem('theme')) {
      setTheme(localStorage.getItem('theme'))
    } else {
      setTheme('theme-dark-blue')
    }

  })();

这里我们检查本地存储中的项目是否存在,如果存在我们使用它,如果不我们设置默认主题类

【讨论】:

  • if(localStorage.getItem("theme") !== null) 检查是否存在; if(localStorage.getItem("theme")) 检查非空字符串。
【解决方案2】:

这是我们需要做的事情

  1. 从本地存储中获取值
  2. 检查是否有效
  3. 如果值无效或缺失,则使用默认值

const validTheme = ['theme-dark-blue', 'theme-dark-green'];

const getThemeFromLocalStorage = () => {
    const savedTheme = localStorage.getItem('theme');

    return validTheme.includes(savedTheme) ? savedTheme : null;
};

setTheme(getThemeFromLocalStorage() || 'theme-dark-blue');

【讨论】:

    【解决方案3】:
       // function to set a given theme/color-scheme
      function setTheme(themeName) {
        // document.documentElement.className = themeName;
        document.getElementById("myDIV").className = themeName;
        localStorage.setItem('theme', themeName);
      }
    
      // Immediately invoked function to set the theme on initial load
      (function () {
        setTheme(localStorage.getItem('theme') || 'theme-dark-blue' );
      })();
    

    【讨论】:

      【解决方案4】:

      最佳猜测。

      据我所知,如果尝试setItem() 某些已从本地存储中删除或不存在的东西,则返回响应为空。

      所以也许可以找到一种编码方式:“如果将一个类添加到我的 HTML 中,则创建一个与该新类同名的 setItem() 并将其添加到 localMemory。” 如果该类存在于本地内存中,getItem() 将确认这一点。如果没有,getItem() 将返回 null。

      所以创建你的 if 语句:"If getItem(className) = null, then set theme-dark-blue"

      【讨论】:

      • 这正是我想要做的,但我的问题是编写实际代码。我理解我正在尝试做的事情背后的概念,但我对 JS 的语法不是很有经验,而且我为做你刚才描述的事情所做的每一次尝试都没有奏效。
      猜你喜欢
      • 2017-08-12
      • 2015-06-29
      • 2012-07-31
      • 2013-11-20
      • 1970-01-01
      • 2021-04-08
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多