获取浏览器可视区域高度,clientHeight等高度问题
主要区分下面几个属性
- clientHeight
- offsetHeight
- window.innerHeight
重点在最后!
1,clientHeight
元素内部的 height
+ 上下内边距。
2,offsetHeight
元素内部的 height
+ 上下内边距 + 上下边框+ 水平滚动条高度。
上面2个都有下面的特性:
- 如果元素或祖先元素有
display:none
,则属性值为 0 - 属性值会被四舍五入为整数值,获取浮点数值需要用
element.getBoundingClientRect()
3,window.innerHeight
浏览器窗口可视区域高度,包括水平滚动条高度。
4,window.getComputedStyle()
- 返回的
style
一个实时的CSSStyleDeclaration
对象,当元素的样式更改时,它会自动更新本身。 style.propName
或style.getPropertyValue(propName)
都可以获取样式值:浮点数值,并且有单位。
window.getComputedStyle(document.documentElement).height
'2868.67px'
5,element.getBoundingClientRect()
- 返回一个
DOMRect
对象,其提供了元素的大小及其相对于视口的位置。 - 返回对象非实时,属性值是浮点数值,以 px 为单位,但不会返回单位。
> $0.getBoundingClientRect()
< DOMRect {x: 854.59375, y: 80, width: 417.40625, height: 812, top: 80, …}
bottom: 892
height: 812
left: 854.59375
right: 1272
top: 80
width: 417.40625
x: 854.59375
y: 80
6,重点
Chrome,火狐,Edge 浏览器表现一致。
document.documentElement.clientHeight
按照上面的说法,当浏览器的内容超过一屏时,document.documentElement.clientHeight
至少也大于window.innerHeight
实际表现:表示浏览器可视区域高度,不包括水平滚动条高度。
也就是说:
- 当有水平滚动条时:
window.innerHeight = document.documentElement.clientHeight + 水平滚动条高度
- 当没有水平滚动条,不考虑上下内边距和上下 border 时:
document.documentElement.offsetHeight === document.body.offsetHeight === document.body.clientHeight
- 不考虑精度和是否带单位时
document.documentElement.offsetHeight ===
document.body.offsetHeight ===
window.getComputedStyle(document.documentElement).height ===
window.getComputedStyle(document.body).height