×

jQuery 如何实现一个滑动按钮开关

作者:Terry2017.01.03来源:Web前端之家浏览:1310评论:0
关键词:JQueryJSjs

滑动开关按钮大家在各大网站都能见到,下面小编给大家分享一篇基于jquery实现的一个滑动按钮开关效果,感兴趣的朋友可以参考下实现代码。

先给大家展示下效果图:

代码:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<title>jquery做的滑动按钮开关</title> 
<link rel="stylesheet" type="text/css" href="bootstrap/bootstrap.min.css"/> 
</head> 
<style> 
.switch{ 
width: 100px; 
margin: 100px 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: #5281cd; 
} 
.off.btn_fath{ 
background-color: #828282; 
} 
</style> 
<body> 
<div class="switch"> 
<div class="btn_fath clearfix on" onclick="toogle(this)"> 
<div class="move" data-state="on"></div> 
<div class="btnSwitch btn1">ON</div> 
<div class="btnSwitch btn2 ">OFF</div> 
</div> 
<div class="btn_fath clearfix off" onclick="toogle(this)"> 
<div class="move" data-state="off"></div> 
<div class="btnSwitch btn1">ON</div> 
<div class="btnSwitch btn2 ">OFF</div> 
</div> 
</div> 
<script type="text/javascript" src="jquery/jquery.min.js"></script> 
<script type="text/javascript" src="bootstrap/bootstrap.min.js"></script> 
<script type="text/javascript"> 
function toogle(th){ 
var ele = $(th).children(".move"); 
if(ele.attr("data-state") == "on"){ 
ele.animate({left: "0"}, 300, function(){ 
ele.attr("data-state", "off"); 
alert("关!"); 
}); 
$(th).removeClass("on").addClass("off"); 
}else if(ele.attr("data-state") == "off"){ 
ele.animate({left: '60px'}, 300, function(){ 
$(this).attr("data-state", "on"); 
alert("开!"); 
}); 
$(th).removeClass("off").addClass("on"); 
} 
} 
</script> 
</body> 
</html>

需要注意的是:

1、这边滑动使用的速度是300ms,好像是匀速,没有线性的快慢那种;试着找下能不能像CSS3中ease那种线性运动的。

2、animate方法中的回调函数,即运动结束后调用的function。

以上所述是小编给大家介绍的jQuery =实现一个滑动按钮开关的功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/svg1483372800716.html

网友评论文明上网理性发言 已有0人参与

发表评论: