纯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>本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!