首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >getBoundingClientRect().top和offsetTop之间的区别?

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

Stack Overflow用户
提问于 2017-05-25 13:05:29
回答 3查看 26.7K关注 0票数 26

getBoundingClientRect().top和offsetTop有什么区别?

https://codepen.io/anon/pen/bWZWQg

代码语言:javascript
复制
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>

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-05-25 13:15:23

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

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

代码语言:javascript
复制
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,同时检查控制台。

如果元素的容器是相对的,则

代码语言:javascript
复制
console.log('offsetTop: ' + elem.offsetTop) // //This is fixed. it get's calculated from beginning of your top most relative container.
票数 24
EN

Stack Overflow用户

发布于 2017-05-25 13:38:57

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

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

票数 12
EN

Stack Overflow用户

发布于 2019-02-15 17:13:29

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

这是一个Related answer

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44172651

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档