我试图获取页面上元素的坐标。我一直在使用的标准的方式来获得它:使用内联偏移量获取元素左侧/顶部的实际偏移量
var el = element, pos = {x: 0, y: 0};
while (el) {
pos.x += el.offsetLeft;
pos.y += el.offsetTop;
el = el.offsetParent;
}
但是,当有问题的元素具有display: block
,并offsetParents之一具有display: inline;
这种方法失败。这是由于在this thread描述的事实:
后一些用jQuery试图事实证明,他们的.offset()
- 方法返回正确的偏移,我已经通过源看了,但不完全是如何发现他们这样做。所以我的问题是:我如何得到确切的位置?我不能在这个项目中使用jQuery,并且the thread described earlier中的方法很麻烦,添加一个元素并且测试工作太多(性能角度),并且使用Element.getBoundingClientRect
也不可用。
如果你喜欢尝试出来,你可以去Apple.com在下面打开您的选择和类型的调试器:
var el, el2;
el = el2 = document.querySelector('#worldwide span');
var pos = {x: 0, y: 0};
while (el2) {
pos.x += el2.offsetLeft;
pos.y += el2.offsetTop;
el2 = el2.offsetParent;
}
alert("Calculated position: " + pos.x + "x" + pos.y + " window size: " + screen.width + "x" + screen.height);
有了这个代码,我得到:Calculated position: 1354x988 window size: 1280x800
(即偏移左边是方式屏幕,它显然不是)
这怎么可能?任何解决方案的想法?约稿?它不一定是确切的,但它必须比以前更好。谢谢。
编辑:这是为了WebKit渲染引擎,澄清。