我正在使用 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/