You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

网页JS实现Dark Mode:.icons类按钮样式切换失效问题求助

Fixing Dark Mode Toggle for .icons Buttons

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: querySelectorAll grabs all elements with the .icons class, then we loop through each one to toggle the darkmode class individually.
  • CSS Fix: .icons.darkmode has higher specificity than just .icons (it combines two class selectors), so its background color will override the base .icons style 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:32:45