
于是就自己写了一个,先看下效果:
提示:您可以先修改部分代码再运行
做法很简单,首先是css布局,动画我没有用jquery的动画,直接用的css3,给变化的 span 和 来回滑动的 i 加上“transition”。css代码如下:
.switch-label{cursor:pointer;}
.switch-label input{display:none;}
.switch-label span{height:21px; line-height:21px; font-family:"微软雅黑"; transition:all 500ms; font-size:14px; display:inline-block; vertical-align:middle; border-radius:4px; overflow:hidden;}
.switch-span{position:relative; border:2px solid red; width:55px; border-radius:2px;}
.switch-span:before,.switch-span:after{position:absolute; z-index:1; color:#fff;}
.switch-span:before{content:"是"; left:5px; top:0;}
.switch-span:after{content:"否"; right:5px; top:0;}
.switch-span i{display:inline-block; position:absolute; border-radius:2px; background:#fff; top:0; width:21px; height:21px; z-index:2; left:0; transition:all 500ms;}
.switch-label.on .switch-span{border-color:#1980B6; background-color:#1980B6;}
.switch-label.on .switch-span i{left:34px;}
.switch-label.off .switch-span{border-color:#B5C1C7; background-color:#B5C1C7;}
.switch-label.off .switch-span i{left:0;}
html代码如下:
<label id="switch" class="switch-label off">
<input checked type="checkbox" />
<span class="switch-span"><i></i></span>
<span> 是否启用过滤条件?</span>
</label>
“是” 和 “否”我使用css的方法加上的。所以html中看不到。jquery代码如下:
<script src="https://5.jimth.com/tpl/js/jquery-1.8.3.min.js"></script>
<script>
$(function(){
$("#switch").click(function(){
var flag = $(this).hasClass("on");
if(flag){
$(this).removeClass("on").addClass("off").find("input").removeAttr("checked");
}else{
$(this).removeClass("off").addClass("on").find("input").attr("checked","checked");
}
return false;
})
})
</script>
原理很简单,我就不多说了。 