javascript - getBoundingClientRect 的负顶部是什么意思?

标签 javascript html css

我正在使用 getBoundingClientRect函数并试图理解它的 top 行为。负顶是什么意思?

在下面的示例中,当您向下滚动时,top 的值变为负值。有人可以解释一下,我如何解释 getBoundingClientRect 中的负最高值?

document.addEventListener("scroll", () => {
  let element = document.getElementById("test");
  let rect = element.getBoundingClientRect();
  console.log(rect.bottom, "bottom....top", rect.top, "...window.innerHeight", window.innerHeight)
});
body {
  height: 100px
}

p {
  width: 100%;
  height: 500px;
  margin-top: 1000px;
}
<p id="test">
  Hello there
</p>

最佳答案

您发布的链接说明了一切:

来自 MDN | Element.getBoundingClientRect (强调我的)

The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

视口(viewport)是窗口/iframe。

所以负值意味着元素的顶部在视口(viewport)顶部滚动到 View 之外。向下滚动时,随着到视口(viewport)顶部的距离变小,顶部值变小。 #test 的上边界碰到视口(viewport)的上边界时,记录的最高值变为零。当您进一步滚动时,该值将变为负值。

我已经用你的例子说明了这一点,我在 #test 段落中添加了一个边框

document.addEventListener("scroll", () => {
  let element = document.getElementById("test");
  let rect = element.getBoundingClientRect();
  console.log("top", rect.top)
});
body {
  height: 100px
}

#test {
  width: 100%;
  height: 50vh;
  margin-top: 50vh;
  margin-bottom: 100vh;
  border: 1px solid black;
}
<p id="test">
  Hello there
</p>

关于javascript - getBoundingClientRect 的负顶部是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57491170/

相关文章:

javascript - 获取自定义事件的 "this"引用

javascript - 通过 POST 将变量传递给模态

html - 我无法移动图像,我该怎么办?

php - 在偶数上添加 tr 元素

css - 拨动开关标签

html - 为什么我的动画属性在 CSS 中不起作用

Javascript (ES6) 模块 : Is it possible to export a variable with a dynamic name?

javascript - 使用 jQuery 查找和替换 HTML

javascript - 在方法中应用媒体查询?

html - TABLE div 的最小高度 100%