首页 > 解决方案 > 暗模式切换 - 两个按钮 - 只有一个有效

问题描述

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

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

可能是因为脚本中的“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);
});

非常感谢大家!

标签: csstoggledarkmodescrypt

解决方案


这是因为你使用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);
});
})

推荐阅读