GetBoundingClientRect, but relative to the entire document

Is there a way to get the rect click for an element relative to the document other than offset? getBoundingClientRect () gets the value relative to the client browser.

I use D3 and jquery height () and width () work (I even tried to do this window.load ()), but offset () is. Also javascripts.offset

return [$e.offset().top + $e.height()/2, $e.offset().left + $e.width()/2] 

$ e.height () and $ e.width () return 0

This is an SVG element, I just use it to edit SVG. It is much easier to load / process SVG with D3. The project is not related to data, it is just a map.

+6
source share
2 answers

Using element.getBoundingClientRect() in and of itself returns the top and left values โ€‹โ€‹that refer to the viewport as you discovered. If you want them to be relative to the document (and not affected by the scroll position), you can add the scroll position using window.scrollY and window.scrollX , for example:

 const rect = element.getBoundingClientRect() rect.left // (relative to viewport) rect.top // (relative to viewport) rect.left + window.scrollX // (relative to document) rect.top + window.scrollY // (relative to document) 

Source

+2
source

Here we use the ES6 method, which returns all the same properties as getBoundingClientRect() , but relative to the entire document.

 const getOffsetRect = (el) => let rect = el.getBoundingClientRect(); // add window scroll position to get the offset position let left = rect.left + window.scrollX; let top = rect.top + window.scrollY; let right = rect.right + window.scrollX; let bottom = rect.bottom + window.scrollY; // polyfill missing 'x' and 'y' rect properties not returned // from getBoundingClientRect() by older browsers if ( rect.x === undefined ) let x = left; else let x = rect.x + window.scrollX; if ( rect.y === undefined ) let y = top; else let y = rect.y + window.scrollY; // width and height are the same let width = rect.width; let height = rect.height; return { left, top, right, bottom, x, y, width, height }; }; 

Note: it also polyfills the details x and y , which are not returned from getBoundingClientRect () by older browsers

0
source

Source: https://habr.com/ru/post/946623/


All Articles