纯css实现开关按钮效果

原理:

  • 选中效果的实现:和文件域(input type=”file”)的美化原理很相似,通过绝对定位将按钮所在层放置于筛选框之上,那么点击这个按钮的同时相当于也选择了复选框
  • 按钮内容:通过css3的:before和:after伪元素和元素的content属性设置按钮的内容。在未选中之前,将:after伪元素的透明度设置为全透明(opacity:0),这时:after伪元素则不显示;反之,也是这样。(这里在css中可以通过attr获取元素的属性值,这个可以借鉴和学习一下)

    一、HTML部分

  1. <div class="switch-box">
  2. <label class="switch-btn">
  3. <input class="checked-switch checked" type="checkbox" name="thumb_status"
  4. value="1" checked ="checked"/>
  5. <span class="text-switch" data-yes="显示" data-no="隐藏"></span>
  6. <span class="toggle-btn"></span>
  7. </label>
  8. </div>

二、CSS部分

  1. div.switch-box{font: 14px "Open Sans", serif; }
  2. /* toggle switch css start */
  3. .switch-btn {position: relative; display: block; vertical-align: top; width: 80px; height: 30px; border-radius: 18px; cursor: pointer;}
  4. .checked-switch {position: absolute; top: 0; left: 0; opacity: 0;}
  5. .text-switch {background-color: #ed5b49; border: 1px solid #d2402e; border-radius: inherit; color: #fff; display: block; font-size: 15px; height: inherit; position:
  6. relative; text-transform: uppercase;}
  7. .text-switch:before, .text-switch:after {position: absolute; top: 50%; margin-top: -.5em;
  8. line-height: 1; -webkit-transition: inherit;
  9. -moz-transition: inherit; -o-transition: inherit; transition: inherit;}
  10. .text-switch:before {content: attr(data-no); right: 11px;}
  11. .text-switch:after {content: attr(data-yes); left: 11px; color: #FFFFFF; opacity: 0;}
  12. .checked-switch:checked ~ .text-switch,.checked-switch.checked ~ .text-switch{background-color: #00af2c; border: 1px solid #068506;}
  13. .checked-switch:checked ~ .text-switch:before,.checked-switch.checked ~ .text-switch:before {opacity: 0;}
  14. .checked-switch:checked ~ .text-switch:after,.checked-switch.checked ~ .text-switch:after {opacity: 1;}
  15. .toggle-btn {background: linear-gradient(#eee, #fafafa); border-radius: 100%; height: 28px; left: 1px; position: absolute; top: 1px; width: 28px;}
  16. .toggle-btn::before {color: #aaaaaa; content: "|||"; display: inline-block; font-size: 12px; letter-spacing: -2px; padding: 4px 0; vertical-align: middle;}
  17. .checked-switch:checked ~ .toggle-btn,.checked-switch.checked ~ .toggle-btn {left: 51px;}
  18. .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;}

预览效果:

开启时的效果:

关闭时的效果: