原理:
- 选中效果的实现:和文件域(input type=”file”)的美化原理很相似,通过绝对定位将按钮所在层放置于筛选框之上,那么点击这个按钮的同时相当于也选择了复选框
- 按钮内容:通过css3的:before和:after伪元素和元素的content属性设置按钮的内容。在未选中之前,将:after伪元素的透明度设置为全透明(opacity:0),这时:after伪元素则不显示;反之,也是这样。(这里在css中可以通过attr获取元素的属性值,这个可以借鉴和学习一下)
一、HTML部分
<div class="switch-box">
<label class="switch-btn">
<input class="checked-switch checked" type="checkbox" name="thumb_status"
value="1" checked ="checked"/>
<span class="text-switch" data-yes="显示" data-no="隐藏"></span>
<span class="toggle-btn"></span>
</label>
</div>
二、CSS部分
div.switch-box{font: 14px "Open Sans", serif; }
/* toggle switch css start */
.switch-btn {position: relative; display: block; vertical-align: top; width: 80px; height: 30px; border-radius: 18px; cursor: pointer;}
.checked-switch {position: absolute; top: 0; left: 0; opacity: 0;}
.text-switch {background-color: #ed5b49; border: 1px solid #d2402e; border-radius: inherit; color: #fff; display: block; font-size: 15px; height: inherit; position:
relative; text-transform: uppercase;}
.text-switch:before, .text-switch:after {position: absolute; top: 50%; margin-top: -.5em;
line-height: 1; -webkit-transition: inherit;
-moz-transition: inherit; -o-transition: inherit; transition: inherit;}
.text-switch:before {content: attr(data-no); right: 11px;}
.text-switch:after {content: attr(data-yes); left: 11px; color: #FFFFFF; opacity: 0;}
.checked-switch:checked ~ .text-switch,.checked-switch.checked ~ .text-switch{background-color: #00af2c; border: 1px solid #068506;}
.checked-switch:checked ~ .text-switch:before,.checked-switch.checked ~ .text-switch:before {opacity: 0;}
.checked-switch:checked ~ .text-switch:after,.checked-switch.checked ~ .text-switch:after {opacity: 1;}
.toggle-btn {background: linear-gradient(#eee, #fafafa); border-radius: 100%; height: 28px; left: 1px; position: absolute; top: 1px; width: 28px;}
.toggle-btn::before {color: #aaaaaa; content: "|||"; display: inline-block; font-size: 12px; letter-spacing: -2px; padding: 4px 0; vertical-align: middle;}
.checked-switch:checked ~ .toggle-btn,.checked-switch.checked ~ .toggle-btn {left: 51px;}
.text-switch, .toggle-btn {transition: All 0.3s ease; -webkit-transition: All 0.3s ease; -moz-transition: All 0.3s ease; -o-transition: All 0.3s ease;}
预览效果:
开启时的效果:
关闭时的效果: