GetBoundingClientRect,但相对于整个文档

GetBoundingClientRect but relative to the entire document

本文关键字:文档 相对于 GetBoundingClientRect      更新时间:2023-09-26

是否有一种方法可以获得相对于文档的元素的客户端rectgetBoundingClientRect()获取相对于客户端浏览器的值。

我使用的是D3jQuery的 height()width()都在工作(我甚至尝试过做window.load()),但offset()是。javascript .offset

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

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

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

使用element.getBoundingClientRect()本身返回相对于视口的topleft值,就像您发现的那样。如果您希望它们相对于文档(而不受滚动位置的影响),您可以使用window.scrollYwindow.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)

这是一个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
  let x = rect.x === undefined ? left : rect.x + window.scrollX;
  let y = rect.y === undefined ? top : 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 };
};

注意:它也多元填充xy的道具,这是不返回从getBoundingClientRect()由旧浏览器