纯Css实现Toggle Switch开关按钮效果
主要根据表单checkbox的checked属性来控制开关的状态和样式的切换。效果如下:
设置一个checkbox表单,利用visibility属性隐藏,然后使用label元素来显示开关按钮的效果。
注意:一个checkbox与其绑定的label,其id="switch"与for="switch"这二个名称要一致。
html设置如下:
<div class="wrap">
<input type="checkbox" id="switch" checked />
<label for="switch">
<span class="txt" turnOn="On" turnOff="Off"></span>
</label>
</div>css部分:
<style>
input[type=checkbox] {
height: 0;
width: 0;
visibility: hidden;
}
label{
cursor: pointer;
width: 110px;
height: 50px;
background: grey;
display: block;
border-radius: 50px;
position: relative;
}
label:after,
.txt::before,
.txt::after {
content: '';
position: absolute;
top: 5px;
left: 5px;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
}
label:after{
background: #fff;
border-radius: 50%;
transition: 0.3s;
}
.txt::before,
.txt::after {
display: block;
color: #fff;
font-weight: bold;
box-sizing: border-box;
}
.txt::before {
content: attr(turnOn);
color: #fff;
}
.txt::after {
content: attr(turnOff);
color: #ccc;
right: 5px;
left: inherit;
}
input:checked+label {
background: #20c997;
}
label:active:after {
width: 40%;
}
input:checked+label:after {
left: calc(100% - 5px);
transform: translateX(-100%);
}
</style>本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!