【网站】给网站添加一个夜间模式切换按钮

使用CSS和JavaScript在明暗模式之间切换。

1.添加CSS

设置<body>元素的样式并创建.dark-mode用于切换

body {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

.dark-mode {
  background-color: black;
  color: white;
}

2。添加JavaScript

获取<body>元素并在.dark-mode之间切换

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

3.完整代码

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

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

<h2>Toggle Dark/Light Mode</h2>
<p>Click the button to toggle between dark and light mode for this page.</p>

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

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

</body>
</html>

4.演示

 

 

 

posted @ 2020-08-06 00:46  木子欢儿  阅读(967)  评论(0编辑  收藏  举报