获取元素在页面的位置

在jquery中获取元素的页面位置,可以很方便的使用offset().left、offset().top来获取,其实在去年有看到过码头的博文:用getBoundingClientRect()来获取页面元素的位置,这技术一不经常用就会忘记了,还是记录在blog,没事翻翻还可以增强记忆,感谢阿里云的朋友。

document.documentElement.getBoundingClientRect

MSDN 中的解释:

Syntax

oRect = object.getBoundingClientRect()

Return Value

Returns a TextRectangle object. Each rectangle has four integer properties (top, left, right, and bottom) that represent a coordinate of the rectangle, in pixels.

Remarks

This method retrieves an object that exposes the left, top, right, and bottom coordinates of the union of rectangles relative to the client’s upper-left corner. In Microsoft Internet Explorer 5, the window’s upper-left is at 2,2 (pixels) with respect to the true client.

该方法现已支持IE6,7,8,FF3.0+和Opera9.5+,我在自己的chrome5上也测试通过。

随后又翻了下jquery 1.4的源代码:下面是jquery1.4.2中关于offset的核心代码:

var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement,

clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,

top  = box.top  + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop ) – clientTop,

left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft) – clientLeft;

return { top: top, left: left };

在IE的标准模式存在一个问题,html元素是有border的,默认是2px,怪癖模式是没有的。所以John Resig大牛考虑到了这一点,就是用clientTop,clientLeft作减值来得到left和top的值。

在不支持getBoundingClientRect的情况下情况更复杂了,要写不少兼容代码~目前主流浏览器基本已经支持getBoundingClientRect方法,有兴趣的朋友可以看一下jquery代码.

jquery中除了offset()外,还提供了另一个取得元素位置的方法position();它跟offset()是不同的,官方文档对position()的解释:

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

这里有一篇文章对position()分析得比较详细,记录一下 http://dotnet.cnblogs.com/page/48103/

2010-07-17备注:原来口碑UED里已经有很详细的解释了,在这里http://ued.koubei.com/?p=948

Leave a Reply