css部分:
.toggle {
display: inline-block;
vertical-align: middle;
position: relative;
box-sizing: border-box;
align-self: center;
width: 52px;
border-radius: 16px;
height: 32px;
}
.toggle-icon {
z-index: 0;
margin: 0;
padding: 0;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border: none;
position: relative;
-webkit-transition: .3s;
transition: .3s;
-webkit-box-sizing: border-box;
box-sizing: border-box;
display: block;
cursor: pointer;
}
.toggle-icon {
width: 52px;
border-radius: 16px;
height: 32px;
background: #e5e5e5;
}
.toggle input[type=checkbox]:checked+.toggle-icon {
background: #007aff;
}
.toggle-icon:after,
.toggle-icon:before {
content: '';
}
.toggle-icon:before {
position: absolute;
left: 2px;
top: 2px;
width: 48px;
height: 28px;
border-radius: 16px;
-webkit-box-sizing: border-box;
box-sizing: border-box;
z-index: 1;
-webkit-transition-duration: .3s;
transition-duration: .3s;
-webkit-transform: scale(1);
transform: scale(1);
}
.toggle-icon:after {
background: #fff;
position: absolute;
z-index: 2;
-webkit-transform: translateX(0);
transform: translateX(0);
-webkit-transition-duration: .3s;
transition-duration: .3s;
}
.toggle-icon:after {
height: 28px;
width: 28px;
top: 2px;
left: 2px;
-webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, .3);
box-shadow: 0 2px 4px rgba(0, 0, 0, .3);
border-radius: 14px;
}
.toggle input[type=checkbox]:checked+.toggle-icon:after {
-webkit-transform: translateX(20px);
transform: translateX(20px);
}
.toggle input[type=checkbox] {
display: none;
}
html部分:
<label class="toggle">
<input type="checkbox" >
<span class="toggle-icon"></span>
</label>
代码都已经贴上,有问题欢迎提问。