本文实例讲述了jQuery中offset()方法用法。分享给大家供大家参考。具体分析如下:
此方法返回或设置所匹配元素相对于document对象的偏移量。
语法结构一:
$(selector).offset()
获取匹配元素在当前document的相对偏移。
返回的对象包含两个整型属:top和left。
此方法只对可见元素有效。
实例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset=” utf-8″>
<meta name=”author” content=”//www.jb51.net/” />
<title>offset()函数-软件开发网</title>
<style type=”text/css”>
*{
margin:0px;
padding:0px;
}
.father{
border:1px solid black;
width:400px;
height:300px;
padding:10px;
margin:50px;
}
.children{
height:150px;
width:200px;
margin-left:50px;
background-color:green;
}
</style>
<script type=”text/javascript” src=”mytest/jQuery/jquery-1.8.3.js”></script>
<script type=”text/javascript”>
$(document).ready(function(){
$(“button”).click(function(){
a=$(“.children”).offset();
alert(“元素的偏移量坐标是:”+a.top+”|”+a.left+””);
})
})
</script>
</head>
<body>
<div class=”father”>
<div class=”children”></div>
</div>
<button>获取元素的坐标</button>
</body>
</html>
以上代码可以弹出子div相对于document的偏移量。
语法结构二:
$(selector).offset(value)
设置匹配元素相对于document对象的坐标。
offset()方法可以让我们重新设置元素的位置。这个元素的位置是相对于document对象的。
如果对象原先的position样式属性是static的话,会被改成relative来实现重定位。
参数列表:










