【问题标题】:GetBoundingClientRect but relative to the entire documentGetBoundingClientRect 但相对于整个文档
【发布时间】:2013-06-01 17:26:22
【问题描述】:

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

我正在使用 D3jQuery 的 height()width() 都在工作(我什至尝试过 window.load()),但 offset() 是。 javascripts .offset 也不是

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

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

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

【问题讨论】:

  • 你有 $e.height().height/2 它应该是 $e.height()/2
  • 这是一个 SVG 元素,还是一个 HTML 元素?你用 D3 做什么?
  • 您的帖子不清楚。什么有效,什么无效?元素是否可见(您不能在隐藏元素上使用 .offset())?

标签: javascript jquery html d3.js


【解决方案1】:

使用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)

Source.

【讨论】:

  • "为了跨浏览器的兼容性,使用window.pageYOffset而不是window.scrollY" - MDN
  • 我同意@vsync 上面的评论,但需要进一步解释。请注意,window.scrollY 实际上是标准。别名window.pageYOffset 跨浏览器兼容,但这是因为window.scrollY 在所有浏览器中都有效,但在IE 中无效(它可能在IE11)。如果你不再迎合 IE,你可以放心地使用window.scrollY
【解决方案2】:

这是一个 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 };
};

注意:它还填充了 xy 属性,旧版浏览器不会从 getBoundingClientRect() 返回

【讨论】:

  • 好方法!尤其是 polyfill!
猜你喜欢
  • 1970-01-01
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 2022-10-13
相关资源
最近更新 更多