getBoundingClientRect().top和offsetTop有什么区别?
https://codepen.io/anon/pen/bWZWQg
const elem = document.querySelector('#find');
console.log('getBoundingClientRect: ' + elem.getBoundingClientRect().top);
console.log('offsetTop: ' + elem.offsetTop);
// Stuff to push the div down the page
<div id='find'>Find me</div>根据我的快速测试,唯一的区别似乎是返回的小数位数。
发布于 2017-05-25 13:15:23
getBoundingClientRect提供相对于客户端视口的偏移,而offsetTop始终是固定的静态属性。尽管当元素在文档上的实际位置改变时它也会改变。要获得真正的澄清,请转到pen,您可以自己检查差异。
如果元素位于相对容器内,则offsetTop将相对于给定的容器pen
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.查看画笔,滚动div,同时检查控制台。
如果元素的容器是相对的,则
console.log('offsetTop: ' + elem.offsetTop) // //This is fixed. it get's calculated from beginning of your top most relative container.发布于 2017-05-25 13:38:57
HTMLElement.offsetTop只读属性返回当前元素相对于offsetParent节点顶部的距离。
getBoundingClientRect()是一个非常有用的跨浏览器安全方法,它可以返回任何元素相对于视口的上、右、下和左位置。
发布于 2019-02-15 17:13:29
getBoundingClientRect方法在性能上可能不如offsetLeft (doc here),但如果你想知道元素在经过CSS变换后的位置,甚至在过渡动画中,它是最好的选择(也许是唯一的方法)。
这是一个Related answer。
https://stackoverflow.com/questions/44172651
复制相似问题