【问题标题】:getBoundingClientRect().top returning wrong valuegetBoundingClientRect().top 返回错误值
【发布时间】:2022-11-08 22:00:41
【问题描述】:

我使用 react js 并尝试使用 getBoundingClientRect().top 获取 dom 元素值。我使用 useEffect 并在里面将 window.scrollY 添加到 getBoundingClientRect().top 中,这样我总是得到相同的值。但它返回错误的值。我尝试只记录 getBoundingClientRect().top 它给了我一个像 155 或类似的值,但正确的值是 2408。代码:

useEffect(() => {
    console.log(containerRef.current.getBoundingClientRect().top);
}, []);

<div className="experience-containter">
  <div ref={containerRef} className="image-container-1">
    <div>
      <img src={image1} alt="" />
    </div>
  </div>
</div>


.experience-containter {
  position: relative;

.image-container-1 {
width: 250px;
height: 250px;
border-radius: 50%;
position: absolute;
right: 15%;
overflow: hidden;

div {
  display: flex;
  justify-content: center;
  align-items: center;
}

img {
  width: 140%;
  object-fit: cover;
  }
 }
}

如您所见,我正在使用 ref 并尝试获取值 containerRef.current.getBoundingClientRect().top。请帮忙

【问题讨论】:

  • 您能否也添加javascript部分。
  • 我只是将其值记录在 useEffect 以检查该值是否正确。我添加了 useEffect 代码

标签: javascript html css reactjs


【解决方案1】:

我不认为使用getBoundingClientRect().top 是接近滚动到元素的正确方法。 getBoundingClientRect() 函数返回相对于窗口而不是整个网页的边界框,因此它可能无法为您提供元素的正确位置。

您可以尝试使用containerRef.current.scrollIntoView() 滚动要查看的元素。如果你想得到偏移值你可以试试containerRef.current.offsetTop + window.scrollY

【讨论】:

  • getBoundingClientRect().top + window.scrollY 给出了很好的结果。我唯一的问题是在初始加载时,chrome 中的值不正确。在 Firefox 中,如果我刷新 2、3 次,我会得到正确的值。这没有任何意义,为什么会发生。
  • 我也尝试过 offsetTop 并且同样的事情正在发生。谷歌浏览器只是拒绝给出正确的值,但在 Firefox 上刷新页面有时会给出正确的值,有时不会。
【解决方案2】:

getBoundingClientRect() 返回相对于窗口(视口)的值,所以如果无论用户如何上下滚动都想准确获取位置,最好获取 getBoundingClientRect() 的值加上文档协调器。

例如使用下面的函数

// get document coordinates of the element
function getCoords(elem) {
  let box = elem.getBoundingClientRect();

  return {
    top: box.top + window.pageYOffset,
    right: box.right + window.pageXOffset,
    bottom: box.bottom + window.pageYOffset,
    left: box.left + window.pageXOffset
  };
}

有关更多信息,您可以在此处参考完整文档 https://javascript.info/coordinates

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 2015-05-12
    • 2017-04-30
    • 2015-05-30
    • 2016-08-13
    • 2022-11-11
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多