javascript 精确获取页面元素的位置
2014-05-23 14:41
681 查看
具体:http://www.verydemo.com/demo_c98_i10256.html
代码如下:
//取得元素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.
随着新锐浏览器都支持IE的getBoundingClientRect方法,我们得以用更简单更快捷更安全的方法来定位页面元素。getBoundingClientRect返回的是一个集合,分别为元素在浏览器可视区的四个角的坐标。
不过它在IE的标准模式存在一个奇怪的问题,html元素是有border的,默认是2px,并且是不可修改的;怪癖模式是没有的。详见http://msdn.microsoft.com/en-us/library/ms536433(VS.85).aspx
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,…………………………………………………………………………
代码如下:
//取得元素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.
随着新锐浏览器都支持IE的getBoundingClientRect方法,我们得以用更简单更快捷更安全的方法来定位页面元素。getBoundingClientRect返回的是一个集合,分别为元素在浏览器可视区的四个角的坐标。
不过它在IE的标准模式存在一个奇怪的问题,html元素是有border的,默认是2px,并且是不可修改的;怪癖模式是没有的。详见http://msdn.microsoft.com/en-us/library/ms536433(VS.85).aspx
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,…………………………………………………………………………
相关文章推荐
- javascript 精确获取页面元素的位置
- javascript 精确获取页面元素的位置
- 用 Javascript 获取指定页面元素的位置
- 用Javascript获取页面元素的位置
- 精确获取页面元素的位置
- 用Javascript获取页面元素的位置
- 精确获取页面元素的位置(转)
- 用 Javascript 获取指定页面元素的位置
- 用Javascript获取页面元素的位置
- 精确获取页面元素的位置
- 用Javascript获取页面元素的位置
- 用Javascript 获取页面元素的位置的代码
- javascript getBoundingClientRect() 来获取页面元素的位置的代码[修正版]第1/2页
- 用Javascript获取页面元素的位置
- 用Javascript获取页面元素的位置
- JavaScript获取页面宽度高度大全 以及元素的位置
- 用Javascript获取页面元素的位置
- javascript getBoundingClientRect() 来获取页面元素的位置的代码[修正版]第1/2页
- 用 Javascript 获取指定页面元素的位置
- 用Javascript 获取页面元素的位置的代码