【问题标题】:How do I make a theme persist even after the page is refreshed?即使在页面刷新后如何使主题持续存在?
【发布时间】:2022-01-31 18:08:05
【问题描述】:

我正在编写 HTML/CSS/JavaScript 代码并想要一个函数或解决方案,以便 当用户刷新页面时主题保持不变。

最好是一个简单的解决方案,因为我是这个领域的初学者。

谢谢。

【问题讨论】:

    标签: javascript html dom frontend web-frontend


    【解决方案1】:

    我不知道您是如何应用主题的,但您可以做的是存储 本地存储中的当前主题,并在页面加载时读取它。

    window.addEventListener("DOMContentLoaded", () => {
      let theme = localStorage.getItem("theme");
      if (theme === "dark") {
        // insert how you apply your theme
      } else {
        // apply other theme
      }
    });
    

    要存储主题,您需要使用 setItem 方法。

    localStorage.setItem("theme", "your value goes here")
    

    希望这就是您想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多