Get the real left / right offset of an element with a built-in offset

I am trying to get the coordinates of an element on a page. I used the standard way to get it:

var el = element, pos = {x: 0, y: 0};
while ( el ) {
    pos.x += el.offsetLeft;
    pos.y += el.offsetTop;
    el = el.offsetParent;
}

But this method fails if this element has display: block, and one of the offsetParents has display: inline;. This is due to what is described in this thread :

The element starts in the middle of the text

jQuery , .offset() , , , . : ? jQuery , , , , - ( ) 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, .

+5
4

WebKit window.webkitConvertPointFromNodeToPage, , , . , node : inline, .

(, , , webkitConvertPointFromNodeToPage WebKit).

, , , display: inline-block, , , .

- , !

Edit:

, , :

var offset = {x: 0, y: 0};
if ( getStyle(el, 'display') == 'inline' ) {
    offset.x = el.offsetLeft - el.parentNode.offsetLeft;
    offset.y = el.offsetTop - el.parentNode.offsetTop;
}

var point = window.webkitConvertPointFromNodeToPage(el, new WebKitPoint(0, 0));

return {
    x: Math.round(point.x + offset.x),
    y: Math.round(point.y + offset.y)
}

inline child offsetTop/Left . , , : , 90% .

- , - .

+2

, , jQuery.offset.

, , offsetLeft offsetTop IE.

, , . , jQuery.offset . , , jQuery.offset .

+1

webkitConvertPointFromNodeToPage , , , neareset, . , , . , , . , , , , ( offsetLeft/Top). , , , , , , SPAN, .

+1
source

I had the same problem. When used $.offset().leftwith jQuery, trying to get the position of a word in a paragraph.

Using $.offset().leftinside the function $(document).ready()gave the wrong result.

Using $.offset().leftin a function $(window).load()solved my problem in WebKit.

This is especially true when image elements or fonts that will affect the layout can be placed.

+1
source

All Articles