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

1,069 阅读1分钟

这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战


【3/10】第三个来了,这次写了一个拉绳的简单动画来开关dark mode,效果如封面所示。

在线预览链接,附源码!

目标依旧是十种方式来实现,顺便提升一下我的水平🙊

大伙见过用过其他形式的dark mode可以发一下,让我见见世面,我也可以复刻一下!

上代码!

很简单的代码,我简单解释一下🦍

🦭HTML

<h1>Mancuoj</h1>
<div id="switch"></div>

🐬SCSS

都一样,SCSS嵌套写起来简单点儿

一些基础设置

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

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

*,
* *,
*::before,
*::after {
  box-sizing: border-box;
}

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

画出开关

伪元素 ::before 可以在所选元素之前或之后添加一些内容。

必须配合 content 来使用,这个属性通常用来给元素添加内容诸如图片或者文字。

content 属性是必需的,用来实现形状时值可以是空字符串

top: -100px,我们藏起来100px长度来做动画✅

#switch {
  position: fixed;
  height: 300px;
  width: 2px;
  background: $bg_color;
  right: 30%;
  top: -100px;
  cursor: pointer;

  &::after {
    content: "";
    position: absolute;
    border: 2px solid $bg-color;
    border-radius: 50%;
    width: 22px;
    height: 22px;
    left: -10px;
    bottom: -20px;
  }
}

写个拉绳的动画

具体可以看animation - CSS(层叠样式表) | MDN (mozilla.org)

动画就是把藏起来的100px放出来再收回去🎈

@keyframes line {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(100px);
  }
  100% {
    transform: translateY(0);
  }
}

.pull {
  animation: line 0.5s ease;
}

dark mode

依旧是最简单的实现,只改了背景和文本的颜色,有需要可以自行添加~

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

🐋JS

JS跟前两个差不多,稍微改改继续用😎

点击时加上动画,完成后再移除,需要用setTimeout()设置一个时间间隔。

const changeTheme = () => {
  const sw = document.getElementById("switch");
  sw.addEventListener("click", () => {
    sw.classList.add("pull");
    if (!document.body.classList.contains("dark")) {
      document.body.classList.add("dark");
      localStorage.setItem("css", "dark");
    } else {
      document.body.classList.remove("dark");
      localStorage.removeItem("css");
    }
    setTimeout(() => {
      sw.classList.remove("pull");
    }, 600);
  });

  if (localStorage.getItem("css")) {
    document.body.classList.add("dark");
  }
};

changeTheme();

前两个的🔗

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

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