Element.getBoundingClientRect 提供其相对于视口 ViewPort 的距离:
- top
- left
- right
- bottom
目前该 api 的兼容性完全够用,可以放心使用
该 api 还提供:
- width
- height
这两个元素和 Element.offsetWidth、Element.offsetHeight 的区别是:正常情况下两个值是一样的,但是如果元素发生了 transform,则 getBoundingClientRect 返回实际页面渲染的高度和宽度。
例如:如果元素的宽 width:100px,变化 transform:scale(0.5),此时 getBoundingClientRect() 将返回宽 50,而 offsetWidth 将返回宽 100.
结合 getBoundingClientRect
和 window.scrollY 就可以计算出元素距离页面顶部的距离。
同理,还存在一个 window.scrollX 的属性,标记 x 轴方向的滚动距离
内联元素为 0. 该宽度包含 padding,不包括 border 和 margin。
Element.clientHeight 同理。这两个元素属性标识 displayed content 的内容
- [Element.offsetWidth]
该宽度包括宽度 + border + padding + vertical scrollbar。不包括 margin 和 伪元素的宽度。
和 Element.offsetHeight 一样,这两个属性标识元素占据了多少空间。
- [Element.scrollWidth]
当元素设置了 visible: true 时元素的总宽度。
- window.scroll
滚动到页面指定位置
- window.scrollBy
按照指定的偏移量进行滚动
将一个元素滚动到视口可视区域。
scrollIntoView 在 IOS 下,兼容性非常差
参考