jQuery 中有两个获取元素位置的方法offset()和position(),这两个方法之间有什么异同

offset():

获取匹配元素在当前视口的相对偏移。

返回的对象包含两个整形属性:top 和 left。此方法只对可见元素有效。
.offset()方法可以让我们重新设置元素的位置。这个元素的位置是相对于document对象的。如果对象原先的position样式属性是 static的话,会被改成relative来实现重定位。

position():

获取匹配元素相对父元素的偏移。

返回的对象包含两个整形属性:top 和 left。为精确计算结果,请在补白、边框和填充属性上使用像素单位。此方法只对可见元素有效。

/ Get *real* offsetParent
var offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= num( this, ’marginTop’ );
offset.left -= num( this, ’marginLeft’ );
// Add offsetParent borders
parentOffset.top += num( offsetParent, ’borderTopWidth’ );
parentOffset.left += num( offsetParent, ’borderLeftWidth’ );
// Subtract the two offsets
results = {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};

使用position()方法时事实上是把该元素当绝对定位来处理,获取的是该元素相当于最近的一个拥有绝对或者相对定位的父元素的偏移位置。
使用position()方法时如果其所有的父元素都为默认定位(static)方式,则其处理方式和offset()一样,是当前窗口的相对偏移
使用offset()方法不管该元素如何定位,也不管其父元素如何定位,都是获取的该元素相对于当前视口的偏移
例如:要显示的元素存放在DOM的最顶端或者最底端(即其父元素就是body),这时用offset()是最好的。

转自:http://www.popo4j.com/article/jQuery-absolute-relative-position.html

posted on 2011-04-28 17:16  如花smile  阅读(12185)  评论(0编辑  收藏  举报