<!-- HTML部分 -->
<div class="switch">
<!-- 复选框用来模拟选中和未选中的状态 -->
<input type="checkbox">
<span class="checked"></span>
</div>
/* css部分 */
.switch {
position: relative;
width: 48px;
height: 22px;
}
input[type=checkbox] {
position: absolute;
margin: 0;
padding: 0;
/* 复选框宽高都为100%,保证点击哪都可以触发移动 */
height: 100%;
width: 100%;
z-index: 99;
opacity: 0;
}
span.checked {
position: absolute;
width: 100%;
height: 100%;
border-radius: 20px;
background-color: #dcdfe6;
z-index: -1;
transition: all .5s;
}
span.checked::before {
content: '';
position: absolute;
top: 2px;
left: 2px;
width: 18px;
height: 18px;
border-radius: 50%;
background-color: #fff;
transition: all .5s;
}
/* 复选框被选中时,让圆圈的left=26px */
input[type=checkbox]:checked+span.checked::before {
left: 26px;
}
/* 复选框被选中时,让开关背景变色 */
input[type=checkbox]:checked+span.checked {
background-color: #57ef10;
}
执行效果:
未解决的问题:
若通过设置animation做打开关闭效果,会有个小问题。由于刷新后,复选框是未选中状态,因此会调off动画,所以我就废弃了这个方法:
/* 复选框选中时,为圆圈添加on动画 */
input[type=checkbox]:checked+span.checked::before {
/* left: 26px; */
animation: on .5s forwards;
}
/* 复选框选中时,为圆圈添加off动画 */
input[type=checkbox]+span.checked::before{
animation: off .5s forwards;
}
@keyframes on {
0% {
left: 2px;
}
100% {
left: 26px;
}
}
/* 一刷新,就走一遍off */
@keyframes off {
0% {
left: 26px
}
100% {
left: 2px;
}
}