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

时间:2017-05-25 05:05:29

标签: javascript

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>

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

4 个答案:

答案 0 :(得分:10)

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

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

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

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

答案 1 :(得分:8)

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

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

否,它将偏移量提供给offsetParent节点,而不是视口。 想象一下,绝对定位的父div顶部为:5000px,您将获得完全不同的结果,而无需触摸滚动条。

相关问题