给你的网页添加一个暗黑模式(壹)

584 阅读1分钟

学习,学习,还是TMD的学习!

如封面,仅仅是一个最简单的实现,还在学习的过程中,目标:10种方式!

在线预览,源码也在😎

废话不多说直接上代码!

一个button标签足矣~

<h1>Mancuoj</h1>
<button id="bt">
  Click it 🔥
</button>

简单设置一下:

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap");

$dark-color: #111;
$light-color: #eee;
$bg-color: #4c6fff;

body {
  margin: 0;
  padding: 0;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: Poppins, serif;
}

h1 {
  margin-right: 20px;
}

button {
  width: 100px;
  height: 40px;
  border: 2px solid $bg-color;
  border-radius: 16px;
  outline: none;
}

设置一下dark mode的颜色~

.dark {
  background-color: $dark-color;
  color: $light-color;
}

写一下点击修改的函数~

const changeTheme = () => {
  const bt = document.getElementById("bt");
  const body = document.body;

  bt.addEventListener("click", () => {
    if (body.className === "dark") {
      body.classList.remove("dark");
    } else {
      body.className = "dark";
    }
  });
};

changeTheme();