网页JS实现Dark Mode:.icons类按钮样式切换失效问题求助
Let's break down why your current code isn't working and how to fix it:
1. Only the first .icons button is getting the darkmode class
Your JavaScript uses document.querySelector(".icons"), which only selects the first element with the .icons class. The other two buttons are completely ignored when you toggle the class.
2. Even if the class was added, the background color wouldn't update
In your CSS, the .icons class's background-color rule comes after the .darkmode rule. Since both are class selectors with equal specificity, the later rule (.icons) overrides the earlier one (.darkmode). So even if the .darkmode class is applied, the original dark background from .icons stays.
Solution Code
Updated JavaScript
Replace the line that toggles .icons with code that targets all three buttons:
document.querySelector(".slider-button").addEventListener("input", function(){ document.querySelector("#data-left").innerHTML = this.value; }) document.querySelector(".slider-button").addEventListener("input", function(){ document.querySelector(".gb-left").innerHTML = 1000-this.value; }) document.querySelector(".button-color-mode").addEventListener("click", function(){ document.body.classList.toggle("darkmode"); // Target all .icons elements and toggle the class on each document.querySelectorAll(".icons").forEach(iconBtn => { iconBtn.classList.toggle("darkmode"); }); })
Updated CSS
Add a specific rule for .icons.darkmode to ensure it takes precedence over the base .icons styles:
body { position: fixed; background-color: hsl(229, 57%, 11%); background-image: url("images/bg-desktop.png"); background-position: center 400px; background-repeat: no-repeat; background-size: cover; } .button-color-mode{ background-color: black; color: white; outline: none; border-radius: 15px; } .darkmode{ background-color: white; } .icons { background-color: hsl(229, 57%, 11%); border-style: none; border-radius: 10px; width: 50px; height: 50px; padding: 10px; margin: 5px; outline: none; } /* Add this rule to override .icons background for dark mode */ .icons.darkmode { background-color: white; }
How It Works
- JavaScript Fix:
querySelectorAllgrabs all elements with the.iconsclass, then we loop through each one to toggle thedarkmodeclass individually. - CSS Fix:
.icons.darkmodehas higher specificity than just.icons(it combines two class selectors), so its background color will override the base.iconsstyle when the class is applied.
Now when you click the mode toggle button, both the body background and all three icon buttons will switch correctly!
内容的提问来源于stack exchange,提问作者Harshit

