JS 一段代码弄懂clientHeight/offsetHeight/scrollHeight的计算方式

 代码

<!DOCTYPE html>
<html lang="zh_CN">
<style>
  .outer{
    width: 100px;height: 100px;
    background: yellow;
    padding:10px;
    margin:15px;
    border:5px solid black;
    overflow: auto;
    /* box-sizing: border-box; */
  }
  .inner{
    height: 20px;
    border-bottom: 1px solid silver;
  }
</style>
<body>
  <div class="outer" id="outer">
    <div class="inner"></div>
    <div class="inner"></div>
    <div class="inner"></div>
    <div class="inner"></div>
    <div class="inner"></div>
    <div class="inner"></div>
    <div class="inner"></div>
    <div class="inner"></div>
    <div class="inner"></div>
    <div class="inner"></div>
  </div>
</body>
<script>
  let outer = document.querySelector('#outer');
  console.log('clientWidth:', outer.clientWidth, 'width: 100px + padding: 10px * 2  - 滚动条宽度');
  console.log('offsetWidth:', outer.offsetWidth, 'width: 100px + padding: 10px * 2 + border: 5px * 2');
  console.log('scrollWidth:', outer.scrollWidth, '横向没有溢出时等于clientWidth');
  
  console.log('clientHeight:', outer.clientHeight, 'height: 100px + padding: 10px * 2'); // 如果有横向滚动条就要减去滚动条宽度了,比如overflow设置为scroll
  console.log('offsetHeight:', outer.offsetHeight, 'height: 100px + padding: 10px * 2 + border: 5px * 2');
  console.log('scrollHeight:', outer.scrollHeight, 'height: 20px * 10 + padding: 10px * 2 + border-bottom: 1px * 10');

  // border-box
//   console.log('clientWidth:', outer.clientWidth, 'width: 100px - border:5px * 2 - 滚动条宽度');
//   console.log('offsetWidth:', outer.offsetWidth, 'width: 100px');
//   console.log('scrollWidth:', outer.scrollWidth, '横向没有溢出时等于clientWidth');
  
//   console.log('clientHeight:', outer.clientHeight, 'height: 100px - border: 5px * 2'); // 如果有横向滚动条就要减去滚动条宽度了,比如overflow设置为scroll
//   console.log('offsetHeight:', outer.offsetHeight, 'height: 100px');
//   console.log('scrollHeight:', outer.scrollHeight, '(height: 20px + border-bottom: 1px) * 10 + padding: 10px * 2');
</script>
</html>

结果

width: 100px; height: 100px; border: 5px; padding: 10px; margin: 15px;

box-sizing: content-box; (padding/border在给定width之外绘制)

box-sizing: border-box; (padding/border在width内绘制)

总结

  1. clientHeight / clientWidth 计算元素内可用区的高度、宽度。(图中黄色部分,包含padding,不计算内容超出元素部分)(滚动条宽度不同环境不一样)
  2. offsetHeight / offsetWidth 计算元素整体占用的高度、宽度。(不包括margin部分)
  3. scrollHeight / scrollWidth 当内容溢出时,计算元素内子节点总高度、宽度,否则等于clientHeight / clientWidth。
  4. 附:window.innerHeight / innerWidth 计算浏览器可视区的高度、宽度

 

若有错误/补充,敬请指出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值