示例网址:
https://50projects50days.com/projects/good-cheap-fast/
http://50projects.tc.cluski.top/50projects50days/good-cheap-fast/
效果:

思路:
布局上没有什么什么好说的,都是常规套路。
在此例子中使用到了邻接兄弟选择器和:checked伪类选择器:
/*当按钮被选择之后,背景色变成紫色*/
.toggle:checked + .label {
background-color: #8e44ad;
}
在按钮开关中,有一个动画:
.ball {
width: 34px;
height: 34px;
border-radius: 50%;
background-color: #fff;
position: absolute;
left: 3px;
animation: sliceOut linear 0.3s forwards;
}
.toggle:checked + .label .ball {
animation: sliceOn linear 0.3s forwards;
}
@keyframes sliceOn {
0% {
transform: translateX(0px) scale(1);
}
50% {
transform: translateX(23px) scale(1.2);
}
100% {
transform: translateX(40px) scale(1);
}
}
@keyframes sliceOut {
0% {
transform: translateX(40px) scale(1);
}
50% {
transform: translateX(23px) scale(1.2);
}
100% {
transform: translateX(0px) scale(1);
}
}
在animation属性的最后,加上了forwards,这样就可以使动画的最后状态被保留住。不然执行完动画之后,还会回退到动画一开始的状态。
id & for
在此例子中,按钮的前面会有一个checkBox,但只是被隐藏了而已。
<div class="toggle-container">
<input type="checkbox" id="good" class="toggle">
<label for="good" class="label">
<div class="ball"></div>
</label>
<span>Good</span>
</div>
为了使点击按钮也可以勾选/不勾选checkBox,这里使用到了id & for的形式。在input元素上指定id,并在其关联的label元素上指定for即可。这样,在点击label的时候,也可以影响到input了。
评论区