前端各种尺寸总结
1、getBoundingClientRect(fractional)
2、offsetWidth(integer、readOnly)
3、scrollWidth(integer、readOnly)
4、clientWidth(integer)
Element.getBoundingClientRect()
1、 x/left, y/top 数值相对的是 viewport;
2、 getBoundingClientRect().width、getBoundingClientRect().height是border+padding+widht/height(content),
标准盒模型:就是border+padding+widht/height(content)
如果box-sizing: border-box,此时的width、height就是border+padding+widht/height(content),所以此时getBoundingClientRect().width== element.width;
3、如果你想得到元素相对于文档左上的数据可以使用
window.scrollX 和 window.scrollY添加到 `top` 和 `left` 属性就可以了
offsetWidth 四舍五入成整数
offsetWidth = width(visible content)+padding+border+scrollBarWidth;pseudo-elements such as `::before` or `::after`
不包含pseudo-elements such as `::before` or `::after`
Note: This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect().
Note: If the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned.
Note: 在不使用transform的情况下,offsetWidth (layout width)约等于getBoundingClientRect (rendering width),
例如:if the element has width: 100px; and transform: scale(0.5);
the getBoundingClientRect()will return 50 as the width, while offsetWidth will return 100
clientWidth
Note: clientWidth = width(content)+padding;clientWidth property is zero for inline elements and elements with no CSS
Note: 可视区域的内容displayed content
Note: clientWidth 使用在html、body上,返回的是视口的尺寸excluding any scrollbar
scrollWidth
a measurement of the width of an element's content, including content not visible on the screen due to overflow.
Note: scrollWidth = contentWidth+padding+pseudo-elements (such as ::before or ::after)width,如果没有滚动条scrollWidth等于clientWidth.
例如: if you need to know the actual size of the content, regardless of how much of it is currently visible, you need to use the Element.scrollWidth and Element.scrollHeight properties.
For example, if a 600x400 pixel element is being displayed inside a 300x300 pixel scrollbox, scrollWidth will return 600 while scrollHeight will return 400.