Javascript getBoundingClientRect()与offsetTop之间的差异?

Javascript getBoundingClientRect()与offsetTop之间的差异?,javascript,Javascript,getBoundingClientRect()与offsetTop之间有什么区别 const elem=document.querySelector(“#find”); log('getBoundingClientRect:'+elem.getBoundingClientRect().top); console.log('offsetTop:'+elem.offsetTop); //将div向下推到页面上的内容 找到我 从我的快速测试来看,唯一的区别似乎是返回的小数位数 getBoundin

getBoundingClientRect()与offsetTop之间有什么区别

const elem=document.querySelector(“#find”);
log('getBoundingClientRect:'+elem.getBoundingClientRect().top);
console.log('offsetTop:'+elem.offsetTop);
//将div向下推到页面上的内容
找到我

从我的快速测试来看,唯一的区别似乎是返回的小数位数

getBoundingClientRect
提供相对于客户端视口的偏移量,而
offsetTop
始终是固定的静态属性。虽然当元素在文档上的实际位置发生变化时,它会发生变化。要得到真正的澄清,请访问pen,您可以自己检查差异

如果元素位于相对容器内,则
offsetTop
将相对于给定容器

查看画笔,滚动div,同时检查控制台

若元素的容器是相对的,那个么

console.log('offsetTop: ' + elem.offsetTop) // //This is fixed. it get's calculated from beginning of your top most relative container.

HTMLElement.offsetTop
只读属性返回当前元素相对于offsetParent节点顶部的距离


getBoundingClientRect()
是一种非常有用的跨浏览器安全方法,可返回任何元素相对于视口的顶部、右侧、底部和左侧位置。

该方法的性能可能不如offsetLeft(),但是如果你想知道一个元素在经过CSS转换后的位置,甚至在过渡动画中的位置,这是最好的选择(也许是唯一的方法)。
这是一个。

“它提供了相对于客户端视口的偏移量,这意味着如果滚动元素并查看,则可以检查差异。笔”

否它为offsetParent节点提供偏移,该节点不是视口。
想象一个绝对位置的父div,top:5000px,你将得到一个完全不同的结果,而不必触摸滚动条。

这是一个注释。这也是一个独立的答案吗?@Enthu你已经有了有效的答案,如果你需要更多的信息,我会很乐意帮助你。是的,那篇文章给出了答案,它正在为我所问的问题工作,但是我还需要一件事,在mousemove上我可以计算出顶部,左边,如果在元素本身的下降中我可以得到顶部,该怎么办,左值。如果你能给任何建议,如果你想我可以创建一个新的职位。谢谢这是错误的
offsetTop
使用position-relative从父元素进行计算,因此,如果将元素包装为具有position:relative的父元素,它将从父元素而不是从页面顶部进行计算。与MDN一样:“HTMLElement.offsetTop只读属性返回当前元素相对于offsetParent节点顶部的距离。”@Aivus答案与画笔中的问题相关。mdn有更一般的答案,答案是完全错误的,是的,它缺少与相对位置相关的细节。但是的,更多的是关于用户提出的问题。
console.log('offsetTop: ' + elem.offsetTop); //This is fixed. it get's calculated from beginning of your page to actual element's position.

console.log('getBoundingClientRect: ' + elem.getBoundingClientRect().top); // this will changing while scroll, because it's relative to your current view port.
console.log('offsetTop: ' + elem.offsetTop) // //This is fixed. it get's calculated from beginning of your top most relative container.