前言
很多场景下,比如手动做一些动画,计算位置等等都需要了解到底需要使用哪些或者哪一个 Api,故收集整理下。
尺寸
Element.clientWidth Or Element.clientHeight
developer.mozilla.org/zh-CN/docs/… developer.mozilla.org/zh-CN/docs/…
- 该属性包括内边距 padding,但不包括边框 border、外边距 margin 和垂直滚动条(如果有的话)。
HTMLElement.offsetWidth Or HTMLElement.offsetHeight
developer.mozilla.org/zh-CN/docs/… developer.mozilla.org/zh-CN/docs/…
- 该属性包括元素的边框(border)、水平线上的内边距(padding)、竖直方向滚动条(scrollbar)(如果存在的话)、以及CSS设置的宽度(width)的值
Element.scrollWidth Or Element.scrollHeight
developer.mozilla.org/zh-CN/docs/… developer.mozilla.org/zh-CN/docs/…
- 包括由于overflow溢出而在屏幕上不可见的内容;
- 它包含元素的内边距,但不包括边框,外边距或垂直滚动条(如果存在);
- 它还可以包括伪元素的宽度,例如
::before或::after; - 如果元素的内容可以适合而不需要水平滚动条,则其
scrollWidth等于clientWidth;
位置
Element.clientLeft Or Element.clientTop
⚠️ 不再被支持!
HTMLElement.offsetLeft Or HTMLElement.offsetTop
developer.mozilla.org/zh-CN/docs/… developer.mozilla.org/zh-CN/docs/…
- 返回当前元素左上角(顶部) 相对于最近的父元素(
[HTMLElement.offsetParent](https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLElement/offsetParent))节点的左边界(顶部)偏移的像素值。
Element.scrollLeft Or Element.scrollTop
developer.mozilla.org/zh-CN/docs/… developer.mozilla.org/zh-CN/docs/…
- 读取或设置元素滚动条到元素左(上)边的距离;
- 设置元素位置还有一个好用的 Api Element.scrollTo() ;
其他
Element.getBoundingClientRect()
- “一键获取” 尺寸位置;
Element.scrollTo()
- 设置元素位置;
- 相似的有:Element.scroll() 、Element.scrollBy()、
Element.scrollIntoView()
- 简单理解就是滚动到可视区域