纯css实现checkbox开关切换按钮

我们都知道 checkbox 标签默认样式 实在是太low了,故对CheckBox美化很有必要。

现提供两种方式对其进行美化。

方法一

<div class="switch-wrap active">
    <span></span>
</div>
.switch-wrap{
  position: relative;
  display: inline-block;
  width: 52px;
  height: 32px;
  border: 1px solid #DFDFDF;
  outline: none;
  border-radius: 16px;
  box-sizing: border-box;
  background: #FFFFFF;
  cursor: pointer;
  transition: border-color .3s,background-color .3s;
  vertical-align: middle;
}
.switch-wrap span{
  position: absolute;
  top: 0;
  left: 0;
  transition: transform 0.3s;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  box-shadow: 0 1px 3px rgba(0,0,0,0.4);
  background-color: #fff;
}
.switch-wrap.active{
  border-color: #33DB70;
  background-color: #33DB70;
}
.switch-wrap.active span{
  transform: translateX(20px);
}

控制切换通过添加类名 active 来控制 

相关jQuery代码为

$(".switch-wrap").click(function(){
    if($(this).hasClass("active")){
       $(this).removeClass("active");
    }else{
      $(this).addClass("active");
    }
})

 

预览地址:https://zuobaiquan.github.io/css3/纯css实现checkbox开关切换按钮/01/index.html

源码地址 https://github.com/zuobaiquan/css3/tree/master/纯css实现checkbox开关切换按钮/01

 

方法二

当点击 label ,光标会根据for 属性指向checkbox中的 id 

<div class='switch-wrap'>
      <input type='checkbox' id= 'switch'>
      <label for='switch'></label>
</div>
.switch-wrap input[type=checkbox]{
  height: 0px;
  width: 0px;
  visibility: hidden;
  margin:0;
  padding:0;
}
.switch-wrap label{
  display: inline-block;
  width: 52px;
  height: 32px;
  border: 1px solid #DFDFDF;
  outline: none;
  border-radius: 16px;
  box-sizing: border-box;
  background: #FFFFFF;
  cursor: pointer;
  transition: border-color .3s,background-color .3s;
  vertical-align: middle;
  position: relative;
}
.switch-wrap label::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  transition: transform 0.3s;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  box-shadow: 0 1px 3px rgba(0,0,0,0.4);
  background-color: #fff;
}
.switch-wrap input:checked + label {
  background: #33DB70;
}
.switch-wrap input:checked + label:before {
  transform: translateX(20px);
}

这里纯粹的是css控制开关切换。无相关的js逻辑代码

预览地址:https://zuobaiquan.github.io/css3/纯css实现checkbox开关切换按钮/02/index.html

源码地址 https://github.com/zuobaiquan/css3/tree/master/纯css实现checkbox开关切换按钮/02

 

总结

方法一利用js控制开关逻辑。通过类名active来实现开关切换。方法二利用checkbox点击来控制开关切换。通过label指向 checkbox的id来控制。其缺点:id具有唯一性;与后端逻辑交互较难控制开关状态。故方法一可取。

posted @ 2018-04-20 10:09  想旅游咯  阅读(4511)  评论(0编辑  收藏  举报