首页 > 解决方案 > 未应用添加到 ClassList 的类

问题描述

我正在尝试制作一个页面,当按下按钮时,按钮的颜色和背景会交换。

document.querySelector("body.light").classList.toggle("dark");
document.querySelector("button.dark").classList.toggle("light");

但即使打开了“暗”类,它也不会应用于背景。我注意到,当我交换 CSS 类(首先放置 .light 类而不是 .dark 类)时,会发生相反的情况,背景颜色会发生变化,但按钮颜色不会发生变化。CSS有问题吗?

这是完整的代码,有一堆console.log 表明这些类确实被添加了:

var darklightArray;

function darklight() {
  darklightArray = document.querySelector("body.light").classList;

  console.log("Before");
  console.log("body: ", document.querySelector("body.light").classList);
  console.log("button: ", document.querySelector("button.dark").classList);

  document.querySelector("body.light").classList.toggle("dark"); //Changes the class to dark, then toggled again turns it light
  document.querySelector("button.dark").classList.toggle("light"); //Toggles the color of the button
  //document.querySelector("button.dark").classList.remove("dark");

  console.log("After");
  console.log("body: ", document.querySelector("body.light").classList);
  console.log("button: ", document.querySelector("button.dark").classList);
  if (darklightArray.length == 2) {
    document.querySelector("button.dark").innerHTML = "To light mode";
  } else {
    document.querySelector("button.dark").innerHTML = "To dark mode";
  }
}
.dark {
  background-color: #07000c;
  color: #D8D8D8;
}

.light {
  background-color: #F9F9F9;
  color: #000000;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title>Darklight Testing</title>
  <link rel="stylesheet" type="text/css" href="../css/darklight_testing.css">
  <script src="darklight_testing.js" defer></script>
</head>

<body class="light">
  <div class="darklight">
    <button type="button" onclick="darklight()" class="dark">To dark mode</button>
  </div>
  Content
</body>

</html>

标签: javascriptcss

解决方案


这行得通。

您可以使用toggleorreplace方法来实现这一点。

MDN 文档供参考

  1. 如果toggle使用,每个元素必须切换两次以添加类和删除类。
  2. 如果replace使用,则一个调用就足够了。

replaceIE、Safari 不支持。

  1. 不要使用类来选择元素。由于您在第一次单击时更改了类,因此无法再次选择元素。考虑使用iddata-属性。

var darklightArray;

function darklight()
{
  var bodyelem = document.body;
  var buttonelem = document.getElementById("toggleButton");

  bodyelem.classList.toggle("dark");
  bodyelem.classList.toggle("light");
  buttonelem.classList.toggle("light");
  buttonelem.classList.toggle("dark");
}
.dark {
  background-color: #07000c;
  color: #D8D8D8;
}

.light {
  background-color: #F9F9F9;
  color: #000000;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title>Darklight Testing</title>
  <link rel="stylesheet" type="text/css" href="../css/darklight_testing.css">
  <script src="darklight_testing.js" defer></script>
</head>

<body class="light">
  <div class="darklight">
    <button type="button" id="toggleButton" onclick="darklight()" class="dark">To dark mode</button>
  </div>
  Content
</body>

</html>


推荐阅读