css - 暗模式切换 - 两个按钮 - 只有一个有效
问题描述
我是新来的,希望你能帮助我:) 基本上我已经创建了一个脚本来检测浏览器的暗模式并相应地显示网页。
此外,应该可以借助按钮在明暗模式之间切换。整个事情都很好,但我想在我的网站上的两个地方集成这个按钮。但只有其中一个有效。
可能是因为脚本中的“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);
});
非常感谢大家!
解决方案
这是因为你使用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);
});
})
推荐阅读
- c++ - 当一个线程不断地从内存中查询一个变量而另一个线程更新它时,是否存在竞争条件?
- ethereum - 将结果形成元掩码
- java - 如何通过套接字java正确地进行非对称加密和解密
- android-studio - 接口 OnSeekBarChangeListner 没有构造函数/没有找到要实现的成员
- json - 角度删除 JSON 对象的空值
- python - 使用相对导入机制,如何在 Python 3 中从父目录导入模块?
- javascript - React - 仅当变量为 true 时才显示类名
- javascript - Prisma 中的嵌套写入
- angular - ng build --base-href serverip/dir : 资产 (css, js, img) 指向服务器 ip
- spring-boot - 你什么时候使用@RequestBody 和@Pathvariable 和@RequestParam