GetBoundingClientRect但相对于整个文档

Joh*_*ohn 10 html javascript jquery d3.js

除了偏移之外,是否有一种方法可以获取相对于文档的元素的客户端rect?getBoundingClientRect()获取相对于客户端浏览器的值.

我正在使用D3和jquery的height()或width()正在工作(我甚至尝试过做window.load()),但是offset()是.也不是javascripts .offset

return [$e.offset().top + $e.height()/2, $e.offset().left + $e.width()/2]
Run Code Online (Sandbox Code Playgroud)

$ e.height()和$ e.width()都返回0

这是一个SVG元素,我只是用它来编辑我的SVG.使用D3加载/处理SVG要容易得多.该项目与数据无关,它只是一张地图.

Ian*_*lor 12

单独使用element.getBoundingClientRect()返回topleft相对于视口的值,就像您发现的那样.如果您希望它们相对于文档(并且不受滚动位置影响),您可以使用window.scrollY和添加滚动位置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)
Run Code Online (Sandbox Code Playgroud)

来源.

  • *“为了跨浏览器兼容性,请使用 `window.pageYOffset` 而不是 `window.scrollY`”* - [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Window/滚动Y#注释) (5认同)
  • 我同意@vsync上面的评论,但需要进一步解释。请注意,“window.scrollY”实际上是标准。别名“window.pageYOffset”是跨浏览器兼容的,但那是因为“window.scrollY”适用于所有浏览器,但不适用于**IE**(它可能适用于**IE11**) 。如果您不再迎合 IE,您可以安全地使用“window.scrollY”。 (2认同)

Dat*_*ter 7

这是一个 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 };
};
Run Code Online (Sandbox Code Playgroud)

注意:它也是 poly-fillingxyprops,旧浏览器不会从 getBoundingClientRect() 返回