【每日一练】225—JS实现一款黑暗模式效果

每日一练10个月前更新 admin
1,661 0

第225练的最终效果:

【每日一练】225—JS实现一款黑暗模式效果

实现代码:

HTML:

<!DOCTYPE html>
<html lang=”en”>
  <head>
    <meta charset=”UTF-8″ />
    <meta http-equiv=”X-UA-Compatible” content=”IE=edge” />
    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″ />
    <title>第225练</title>
    <link rel=”stylesheet” href=”index.css” />
  </head>
  <body>
    <input type=”checkbox” id=”dark-mode” class=”input” />
    <label for=”dark-mode” class=”label”>
      <div class=”circle”></div>
    </label>
    <script src=”index.js”></script>
  </body>
</html>

CSS:

body {
  margin: 0;
  display: flex;
  justify-content: center;
  height: 100vh;
  align-items: center;
  transition: .4s;
}
.input {
  visibility: hidden;
}
.label {
  position: absolute;
  width: 80px;
  height: 40px;
  background-color: lightgray;
  border-radius: 20px;
  cursor: pointer;
}
.circle {
  width: 34px;
  background-color: white;
  height: 34px;
  border-radius: 50%;
  top: 3px;
  position: absolute;
  left: 3px;
  animation: toggleOff 0.4s linear forwards;
}
.input:checked + .label {
  background-color: white;
}
.input:checked + .label .circle {
  animation: toggleOn 0.4s linear forwards;
  background-color: black;
}
@keyframes toggleOn {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(40px);
  }
}
@keyframes toggleOff {
  0% {
    transform: translateX(40px);
  }
  100% {
    transform: translateX(0);
  }
}

JS:

const inputEl = document.querySelector(“.input”);
const bodyEl = document.querySelector(“body”);
inputEl.checked = JSON.parse(localStorage.getItem(“mode”));
updateBody();
function updateBody() {
  if (inputEl.checked) {
    bodyEl.style.background = “black”;
  } else {
    bodyEl.style.background = “white”;
  }
}
inputEl.addEventListener(“input”, () => {
  updateBody();
  updateLocalStorage();
});
function updateLocalStorage() {
  localStorage.setItem(“mode”, JSON.stringify(inputEl.checked));
}
© 版权声明

相关文章

暂无评论

暂无评论...