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与IE8中进行):
1、标准模式,没有重设html的border
[Ctrl+A 全选 提示:你可先修改部分代码,再按运行]
2、标准模式,重设html的border
[Ctrl+A 全选 提示:你可先修改部分代码,再按运行]
3、怪癖模式,没有重设html的border
[Ctrl+A 全选 提示:你可先修改部分代码,再按运行]
4、怪癖模式,重设html的border
[Ctrl+A 全选 提示:你可先修改部分代码,再按运行]
John Resig给出的方案就是用clientTop,clientLeft作减值。以下函数就是从JQuery中抠出来,就后就用它获取页面元素的坐标,比offset大法安全多了。
复制代码 代码如下:
var getCoords = function(el){ var box = el.getBoundingClientRect(), doc = el.ownerDocument, body = doc.body, html = doc.documentElement, clientTop = html.clientTop || body.clientTop || 0, clientLeft = html.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || html.scrollTop || body.scrollTop ) - clientTop, left = box.left + (self.pageXOffset || html.scrollLeft || body.scrollLeft) - clientLeft return { 'top': top, 'left': left }; };
其中self.pageYOffset相当于window.self.pageYOffset,是火狐的一个属性,相当于document.body.scrollTop。以下是它的定义: Definition: The pageYOffset property is used to determine the Y coordinate of the scroll position in some browsers. This is not a reserved word so you can declare your own variable or function called pageYOffset but if you do then you will not be able to find or alter the scroll position of a window in some browsers