【问题标题】:Set default theme on initial load JS在初始加载 JS 上设置默认主题
【发布时间】:2021-05-31 06:18:11
【问题描述】:

如果 localStorage 中没有先前设置的主题(针对新访问者),我正在尝试将我的网站主题设置为“theme-dark-purple”。但是,我现在的代码不起作用,我不知道为什么。

每个主题都有相应的带有 onclick 功能的按钮,但我没有在此处包含它,因为按钮可以正常工作,我不想在此处添加已经可以工作的代码。

<script>
  // 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 default theme as 'theme-dark-purple' if there's no set theme
  (function () {
    if (localStorage.getItem('theme') != 'theme-dark-purple', 'theme-light-purple', 'theme-dark-blue', 'theme-light-blue') {
      setTheme('theme-dark-purple');
    }
  })();
</script>

【问题讨论】:

    标签: javascript html wordpress local-storage


    【解决方案1】:

    其实你写条件的方式是错误的。你可以试试这个。

      (function () {
        const themes = ['theme-dark-purple', 'theme-light-purple', 'theme-dark-blue', 'theme-light-blue'];
        if (!themes.includes(localStorage.getItem('theme'))) {
          setTheme('theme-dark-purple');
        }
      })();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      相关资源
      最近更新 更多