html 如何确定精确坐标,javascript 精确获取页面元素的位置

//取得元素x坐标

function pageX(elem) {

return elem.offsetParent?(elem.offsetLeft+pageX(elem.offsetParent)):elem.offsetLeft;

}

//取得元素y坐标

function pageY(elem) {

return elem.offsetParent?(elem.offsetTop+pageY(elem.offsetParent)):elem.offsetTop;

}

貌似这位大神在出这本书时比较赶,有许多纰漏,最后大神也发觉这两个函数有问题,并没有把它们运用到JQuery中。由于是用累加的方式去计算,只要一个元素出现问题,就有可能层层被大,因此我在精确获取样式属性时就摒弃这种方法。主要误算参照大神的结论:

Handling table border offsets.

Fixed positioned elements.

Scroll offsets within another element.

Borders of overflowed parent elements.

Miscalculation of absolutely positioned elements.

8f32c5466cbd110d982e1d37b1cc26d3.png

随着新锐浏览器都支持IE的getBoundingClientRect方法,我们得以用更简单更快捷更安全的方法来定位页面元素。getBoundingClientRect返回的是一个集合,分别为元素在浏览器可视区的四个角的坐标。

不过它在IE的标准模式存在一个奇怪的问题,html元素是有border的,默认是2px,并且是不可修改的;怪癖模式是没有的。详见http://msdn.microsoft.com/en-us/library/ms536433(VS.85).aspxThis 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

getBoundingClientRect

运行代码

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]

2、标准模式,重设html的border

getBoundingClientRect

运行代码

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]

3、怪癖模式,没有重设html的border

getBoundingClientRect

运行代码

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]

4、怪癖模式,重设html的border

getBoundingClientRect

运行代码

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值