您的位置:首页 > Web前端 > JQuery

第一次写插件,基于jQuery的

2011-07-26 17:11 190 查看
<!DOCTYPE html>

<html>
<head>
<title></title>
<style>
#content{
width:960px; margin:0 auto; height:30px; border:solid 1px Red; background:red; position:relative;
}
#floatTest{
background:Yellow;
border:solid 1px Red;
height:50px;
right:10px;
position:absolute;
top:30px;
width:200px;
z-index:100;
}

</style>
<script src="http://zxj2634.blog.163.com/blog/Scripts/jq.min.js" type="text/javascript"></script>
<script type="text/javascript">
/**
* 要求,有个父元素 position 为 relative
* 参数 distanceTop 距离顶端距离(为空则默认为0)
* @example
* $("#floatTest").float("20px");
*/
jQuery.fn.floatTest = function (distanceTop) {
var $this = $(this); //这里的this是指当前的jQuery对象
var initTop = $this.css("top");
var lengthTop;
//先取得距离顶部的高度lenghtTop = 父元素的高度 + 父元素距离顶部的高度
var getParent = $this.parent();
if (typeof distanceTop === "undefined") {
lengthTop = getParent.attr("offsetTop") + getParent.height();
} else {
var space = parseInt(distanceTop);
lengthTop = getParent.attr("offsetTop") + getParent.height() - space;
}
//页面滚动
$(window).scroll(function () {
var changeTop = $(window).scrollTop();
//滚动的高度小于初始高度
if (changeTop < lengthTop) {
$this.animate({ top: initTop }, 10);
} else { //滚动的高度小于初始高度
var toTop = (parseInt(initTop) + changeTop - lengthTop) + "px";
$this.animate({ top: toTop }, 10);
}
});
}
$(function () {
$("#floatTest").floatTest("20px");
})
</script>
</head>
<body style="margin:0">
<div style="height:200px;"></div>
<div id="content">
<div id="floatTest" style="">aaaa</div>
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: