You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

scrollHeight是否会小于clientHeight或offsetHeight?三者取最大值是否恒等于scrollHeight?

结论

你编写的Math.max(el.scrollHeight, el.offsetHeight, el.clientHeight)不会永远返回el.scrollHeight,scrollHeight完全存在比另外两个属性值更小的场景。


原因说明

先明确三个高度属性的核心定义:

  • clientHeight:元素可视区域高度,包含内边距,不包含边框、外边距、水平滚动条高度
  • offsetHeight:元素在文档流中占据的总高度,包含内边距、边框、水平滚动条高度,不包含外边距
  • scrollHeight:元素所有内容的总高度(包括被滚动隐藏的部分),包含内边距,不包含边框、外边距

常见scrollHeight更小的场景:

  1. 元素内容高度小于容器可视高度时
    只要元素内容没有溢出容器,scrollHeight就等于clientHeight,此时如果元素有边框、或者存在水平滚动条,offsetHeight = clientHeight + 上下边框高度 + 水平滚动条高度,显然scrollHeight < offsetHeight,此时Math.max的返回值就是offsetHeight而非scrollHeight。
    举个简单的示例:
.test-box {
  height: 100px;
  padding: 10px;
  border: 5px solid #000;
  overflow: auto;
}

此时.test-box的clientHeight = 120px(100 + 102),offsetHeight = 130px(120 + 52),如果内部只有一行高度20px的文字,scrollHeight = 120px,明显小于offsetHeight。
2. 根元素<html>的特殊场景
你提到的<html>元素clientHeight > offsetHeight的少数场景下,也可能出现scrollHeight小于另外两个属性的情况:比如页面内容高度小于视口高度时,<html>的scrollHeight等于视口高度,此时如果有特殊的根元素样式配置,就会出现scrollHeight更小的情况。


内容的提问来源于stack exchange,提问作者Jake Todaro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 20:36:04