首页 > 解决方案 > 网页上通过JS的暗模式

问题描述

我一直在尝试在练习网页上添加暗模式,它可以更改正文背景颜色,但不适用于按钮,代码是:

该代码不适用于 .icons CSS 类,它出现在 chrome 中,但不起作用,

高度赞赏解释。

谢谢你

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");
  document.querySelector(".icons").classList.toggle("darkmode");
})
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;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@400;700&display=swap" rel="stylesheet">
  <link rel="icon" href="images/favicon-32x32.png">
  <link rel="stylesheet" href="styles.css">
  <title>Fylo Data Storage</title>
</head>

<body>
      <button class="icons" type="button"><img src="images/icon-document.svg" alt="" name="button"></button>
      <button class="icons" type="button"><img src="images/icon-folder.svg" alt="" name="button"></button>
      <button class="icons" type="button"><img src="images/icon-upload.svg" alt="" name="button"></button>
</html>

标签: javascripthtmlcssdarkmode

解决方案


在 CSS 中,定义选择器的顺序很重要。当一个规则(例如background-color)在具有相同特性的多个选择器中定义时,最后定义的选择器将覆盖任何先前的定义。

在这种情况下,在 之后.icons { background-color: ... }定义,因此即使还设置了类也“获胜”。 .darkmode { background-color: ... }.iconsdarkmode

换句话说:将.darkmode-block 移到 -block 下方.icons


推荐阅读