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>
Run Code Online (Sandbox Code Playgroud)
从我的快速测试中,唯一的区别似乎是返回的小数位数.
Meh*_*shi 11
它为您提供相对于客户端视口的偏移量,这意味着如果您滚动元素并查看,则可以检查差异. 钢笔
console.log('offsetTop: ' + elem.offsetTop); //This is fixed.
console.log('getBoundingClientRect: ' + elem.getBoundingClientRect().top); // this is changing while scroll
Run Code Online (Sandbox Code Playgroud)
看到笔,滚动div然后检查控制台.
的HTMLElement.offsetTop只读属性返回电流元件相对于offsetParent节点的顶部的距离.
getBoundingClientRect() 是一个非常有用的跨浏览器安全方法,它返回任何元素相对于视口的顶部,右侧,底部和左侧位置.