getBoundingClientRect()。top和offsetTop之间的区别?

问题描述 投票:13回答:4

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>

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

javascript
4个回答
10
投票

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

console.log('offsetTop: ' + elem.offsetTop); //This is fixed.

console.log('getBoundingClientRect: ' + elem.getBoundingClientRect().top); // this is changing while scroll

看到笔,滚动div然后检查控制台。


8
投票

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

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


0
投票

方法getBoundingClientRect在性能上可能不如offsetLeft(doc here),但是如果你想知道一个元素在被CSS转换后的位置,或者甚至仍然在转换动画中,它是最好的选择(也许是唯一的方法)。 这是一个Related answer


0
投票

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

不,它给offsetParent节点提供了偏移量,而该节点不是视口。想象一下绝对位置的父div与top:5000px,你会得到一个完全不同的结果而不触及滚动条。

© www.soinside.com 2019 - 2024. All rights reserved.