Jquery开关按钮的实现
一.效果图
如图
二.代码详解
<div class=\"switch\"><h2>默认打开</h2><div class=\"btn_fath clearfix on\" id=\"1\" onclick=\"toogle(this)\"><div class=\"move\" data-state=\"on\"></div><div class=\"btnSwitch btn1\">开</div><div class=\"btnSwitch btn2 \">关</div></div><h2>默认关闭</h2><div class=\"btn_fath clearfix off\" id=\"2\" onclick=\"toogle(this)\"><div class=\"move\" data-state=\"off\"></div><div class=\"btnSwitch btn1\">开</div><div class=\"btnSwitch btn2 \">关</div></div></div><script type=\"text/javascript\">function toogle(th) {//根据this对象获取到节点move的css,然后对css进行操作,实现按钮滑动开关的效果var ele = $(th).children(\".move\");if (ele.attr(\"data-state\") == \"on\") {//获取到按钮的名称和开关状态,进行后台操作;设置关的状态=0,开=1var name = th.id;var status = \"0\";$.ajax({url:\'xxx?status=\'+status+\'&name=\'+id,type:\'post\',dateType:\'json\',success:function(xxx){xxx}});ele.animate({left: \"0\"}, 300, function() {ele.attr(\"data-state\", \"off\");});$(th).removeClass(\"on\").addClass(\"off\");} else if (ele.attr(\"data-state\") == \"off\") {ele.animate({left: \'60px\'}, 300, function() {$(this).attr(\"data-state\", \"on\");});$(th).removeClass(\"off\").addClass(\"on\");}}</script>//开关css配置<style>.switch {width:100px;margin:50px 0px 0 100px;}.btn_fath {margin-top:10px;position:relative;border-radius:20px;}.btn1 {//“开”字的位置float:left;}.btn2 {//“关”字的位置float:right;}.btnSwitch {height:40px;width:50px;border:none;color:#fff;line-height:40px;font-size:16px;text-align:center;z-index:1;}.move {//按钮的设置z-index:100;width:40px;border-radius:20px;height:40px;position:absolute;cursor:pointer;border:1px solid #828282;background-color:#f1eff0;box-shadow:1px 2px 2px 1px #fff inset,0 0 5px 1px #999;}.on .move {left:60px;}.on.btn_fath {//开启效果的背景background-color:#44b549;height:43px}.off.btn_fath {//关闭效果的背景background-color:#828282;height:43px}</style>
主要参考来源:http://www.jq22.com/webqd636