20

Is there a method for getting the client rect for an element relative to the document besides offset? getBoundingClientRect() gets the value relative to the client's browser.

I'm using D3 and jQuery's height() nor width() are working (I've even tried doing it window.load()), but offset() is. Neither are javascripts .offset

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

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

It's an SVG element, I'm just using it to edit my SVG. It's much easier to load/handle SVG's with D3. The project is not data related, it's just a map.

4

2 回答 2

26

就像您发现的那样,单独使用与视口相关的返回element.getBoundingClientRect()top和值。left如果您希望它们与文档相关(并且不受滚动位置的影响),您可以使用window.scrollYand添加滚动位置window.scrollX,如下所示:

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)

来源

于 2016-04-09T18:30:28.523 回答
8

这是一个 ES6 方法,它返回与整个文档相同getBoundingClientRect()但相对于整个文档的所有属性。

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 };
};

注意:它还填充了旧版浏览器不会从 getBoundingClientRect() 返回的xand道具y

于 2017-09-11T12:16:47.253 回答