我試圖獲取頁面上元素的座標。我一直在使用的標準的方式來獲得它:使用內聯偏移量獲取元素左側/頂部的實際偏移量
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渲染引擎,澄清。