原理:
利用css的伪元素生成一个按钮,根据表单checkbox的checked属性来控制开关的状态和样式的切换。
代码:
html部分:
<input type="checkbox" class="switch-button" id="switch-button" onclick="handleClick(this)">
<label for="switch-button"></label>
一个checkbox与其绑定的label,主要样式是通过label实现的;
css部分:
.switch-button{
display: none;/*隐藏表单元素*/
}
.switch-button+label{/*+选择器选择紧跟“+”左边选择器的第一个元素*/
display: inline-block;
position: relative;
transition: all .3s;
width: 60px;
height: 30px;
border: 1px solid #999;
border-radius: 15px;
background-color: #ccc;
}
.switch-button:checked+label{/*选中表单后的样式,:checked表示checkbox被选中后的状态*