【问题标题】:Day Mode and Night Mode日间模式和夜间模式
【发布时间】:2022-11-10 10:20:56
【问题描述】:

我尝试使用复选框按钮创建白天模式和夜间模式。它运作良好。默认模式是白天模式,但问题是当我处于夜间模式然后刷新页面或转到网站上的其他页面时,它将回到白天模式

JavaScript

const themeToggler = document.querySelector(".theme-toggler");

//Change Theme
themeToggler.addEventListener("click", () => {
  document.body.classList.toggle("dark-theme-variables");
  themeToggler.querySelector("span:nth-child(1)").classList.toggle("active");
  themeToggler.querySelector("span:nth-child(2)").classList.toggle("active");
});

【问题讨论】:

标签: javascript


【解决方案1】:

这是预期的行为,通过 JavaScript 进行的状态更改不会在站点重新加载之间保留。

您需要某种机制,将首选模式存储在客户端设备上。

据我所知,有两种方法可以做到这一点:

使用 LocalStorage 的示例(来自 mdn):

// Stores "Tom" in "myCat"
localStorage.setItem("myCat", "Tom");

// Retrieves whatever is in "myCat":
const cat = localStorage.getItem("myCat");

根据您的用例进行调整,您可以执行以下操作:

const themeToggler = document.querySelector(".theme-toggler");

//Change Theme
themeToggler.addEventListener("click", () => {
  document.body.classList.toggle("dark-theme-variables");

  const is_dark_mode = document.body.classList.contains(
    "dark-theme-variables"
  )

  // storing the user's preference in LocalStorage
  window.localStorage.setItem("dark-mode", is_dark_mode)
});

稍后您可以检索该值并调整<body> 的类:

const wants_dark_mode = window.localStorage.getItem("dark-mode") === true

if (wants_dark_mode) {
  document.body.classList.add("dark-theme-variables")
}

【讨论】:

    【解决方案2】:

    我只想问你是否找到解决办法。我有同样的问题和相同的代码。我可以看看你是怎么做的吗

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多