📜  基础 CSS 无线电开关(1)

📅  最后修改于: 2023-12-03 15:23:40.909000             🧑  作者: Mango

基础 CSS 无线电开关

CSS 是一种用来描述网页的样式的语言,无线电开关是 CSS 中一种简单的动画效果。在这篇文章中,我们将会介绍基础 CSS 无线电开关的实现方法。

实现原理

基础 CSS 无线电开关的实现原理是基于 CSS 中的 checkboxlabel 元素。在 HTML 中,我们可以创建一个 checkbox 元素和一个 label 元素,并将它们绑定起来。当用户点击 label 元素时,checkbox 元素的状态会改变。我们可以利用这个特性来创建一个开关的效果。

同时,我们可以利用 CSS 中的 :checked 伪类来控制动画效果。当 checkbox 元素被选中时,我们可以让 switch 元素的背景色、位置等属性发生变化,并实现一些简单的动画效果。

实现步骤
  1. 创建一个 checkbox 元素和一个 label 元素,并将它们绑定起来。
<input type="checkbox" id="switch">
<label for="switch"></label>
  1. 使用 CSS 设置 label 元素的样式,并将其定位到 checkbox 元素上方。
label {
  position: absolute;
  top: 0;
  left: 0;
  width: 40px;
  height: 20px;
  background-color: gray;
  border-radius: 10px;
}
  1. 使用 CSS 设置 label 元素的 ::before 伪元素,以实现 switch 按钮的样式。
label::before {
  content: "";
  position: absolute;
  top: 2px;
  left: 2px;
  width: 16px;
  height: 16px;
  background-color: white;
  border-radius: 50%;
  transition: transform 0.2s;
}
  1. 使用 CSS 中的 :checked 伪类,当 checkbox 元素被选中时,改变 label 元素和 ::before 伪元素的样式。
#switch:checked + label {
  background-color: skyblue;
}

#switch:checked + label::before {
  transform: translateX(20px);
}
  1. 将界面美化,并实现更多的动画效果。
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

label {
  position: relative;
  cursor: pointer;
  box-shadow: 0 0 10px rgba(0,0,0,0.2);
}

label::before {
  box-shadow: 0 0 10px rgba(0,0,0,0.2);
}

#switch:checked + label::before {
  background-color: skyblue;
}
完整代码
<input type="checkbox" id="switch" class="switch">
<label for="switch" class="switch-label"></label>
.switch {
  display: none;
}

.switch-label {
  position: relative;
  display: inline-block;
  width: 54px;
  height: 30px;
  background-color: #ddd;
  border-radius: 30px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.switch-label::before {
  content: "";
  position: absolute;
  top: 1px;
  left: 1px;
  width: 28px;
  height: 28px;
  background-color: white;
  border-radius: 50%;
  transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), background-color 0.3s;
}

.switch-label::after {
  content: "";
  position: absolute;
  top: 5px;
  left: 5px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0,0,0,0.2);
  transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), background-color 0.3s, box-shadow 0.3s;
}

.switch:checked + .switch-label {
  background-color: #5EB6E2;
}

.switch:checked + .switch-label::before {
  background-color: #fff;
  left: 26px;
}

.switch:checked + .switch-label::after {
  background-color: #5EB6E2;
  left: 29px;
  box-shadow: 0 0 10px rgba(0,0,0,0.2);
}
展示效果

点击 switch 开关,展示简单的动画效果。