【问题标题】:Darkmode toggle - two buttons - only one works暗模式切换 - 两个按钮 - 只有一个有效
【发布时间】:2021-10-22 07:27:13
【问题描述】:

我是新来的,希望你能帮助我:) 基本上我已经创建了一个脚本来检测浏览器的暗模式并相应地显示网页。

此外,应该可以借助按钮在明暗模式之间切换。整个事情都很好,但我想在我的网站上的两个地方集成这个按钮。但只有其中一个有效。

可能是因为脚本中的“const”属性。但是,我不知道我必须改变什么。

你们中有人有想法吗?附件是一个显示问题的jsfiddle: https://jsfiddle.net/ubL63k0g/

JS:

const btn = document.querySelector(".btn-toggle-darkmode");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");

const currentTheme = localStorage.getItem("theme");
if (currentTheme == "dark") {
  document.body.classList.toggle("dark-theme");
} else if (currentTheme == "light") {
  document.body.classList.toggle("light-theme");
}

btn.addEventListener("click", function() {
  if (prefersDarkScheme.matches) {
    document.body.classList.toggle("light-theme");
    var theme = document.body.classList.contains("light-theme") ?
      "light" :
      "dark";
  } else {
    document.body.classList.toggle("dark-theme");
    var theme = document.body.classList.contains("dark-theme") ?
      "light" :
      "dark";
  }
  localStorage.setItem("theme", theme);
});

非常感谢大家!

【问题讨论】:

    标签: css toggle darkmode scrypt


    【解决方案1】:

    这是因为你使用document.querySelector(".btn-toggle-darkmode"); 这将得到一个元素,所以它只听一个。 你必须使用document.querySelectorAll(".btn-toggle-darkmode");

    const btns = document.querySelectorAll(".btn-toggle-darkmode");
    const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
    
    const currentTheme = localStorage.getItem("theme");
    if (currentTheme == "dark") {
    console.log(currentTheme)
      document.body.classList.toggle("dark-theme");
    } else if (currentTheme == "light") {
      document.body.classList.toggle("light-theme");
    }
    
    btns.forEach(function(btn){
    btn.addEventListener("click", function() {
      if (prefersDarkScheme.matches) {
        document.body.classList.toggle("light-theme");
        var theme = document.body.classList.contains("light-theme") ?
          "light" :
          "dark";
      } else {
        document.body.classList.toggle("dark-theme");
        var theme = document.body.classList.contains("dark-theme") ?
          "light" :
          "dark";
      }
      localStorage.setItem("theme", theme);
    });
    })
    

    【讨论】:

    • 是的,但我会在按钮中重命名 btn,因为它现在是一个数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2015-03-07
    • 1970-01-01
    相关资源
    最近更新 更多