深色模式和浅色模式html、css、javascript怎么样?

Dark mode and light mode html, css, javascript how?

您好,提前谢谢您, 我想制作一个带有暗模式的按钮,如果你点击它,它就会变成暗模式,然后按钮被称为白色模式,然后当你再次点击它时,它变成白色模式,按钮再次被称为暗模式。

代码:

<!DOCTYPE html> 
<html>
<head>
<style>
.page {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

.dark-mode {
  background-color: black;
  color: white;
}
</style>
</head>
<body>

<div class="page">Hello</div>

<button onclick="myFunction()">dark mode</button>

<script>
function myFunction() {
   var element = document.page;
   element.classList.toggle("dark-mode");
}
</script>

</body>
</html>

您正试图在 document.page 上切换 dark-mode class,这不存在。

相反,您应该在 document.body 上切换它。

<!DOCTYPE html> 
<html>
<head>
<style>
.page {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

.dark-mode {
  background-color: black;
  color: white;
}
</style>
</head>
<body>

<div class="page">Hello</div>

<button onclick="myFunction()">dark mode</button>

<script>
function myFunction() {
   var element = document.body;
   element.classList.toggle("dark-mode");
}
</script>

</body>
</html>

要仅在 div 上切换 class,请使用 querySelector:

<!DOCTYPE html> 
<html>
<head>
<style>
.page {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

.dark-mode {
  background-color: black;
  color: white;
}
</style>
</head>
<body>

<div class="page">Hello</div>

<button onclick="myFunction()">dark mode</button>

<script>
function myFunction() {
   var element = document.querySelector('div.page');
   element.classList.toggle("dark-mode");
}
</script>

</body>
</html>

function myFunction() {
   var element = document.body;
   element.classList.toggle("dark-mode");
   if (element.classList.contains("dark-mode")){
    document.getElementById('btn').innerHTML = "Light Mode";
   }
   else{
    document.getElementById('btn').innerHTML = "Dark Mode";
   }
}
.page {
  display:inline;
  background:#FFF;
  color: #121212;
  font-size: 25px;
}

.dark-mode,
.dark-mode .page {
  background-color:#202020;
  color: #FFF;
}
<!DOCTYPE html> 
<html>
<head>
</head>
<body>
<div class="page">Hello</div>
<br><br><br>
<button onclick="myFunction()" id="btn">Dark mode</button>
</body>
</html>