获取盒子的实际大小的几种方式

520 阅读2分钟

html 结构

<style>
  * {
    margin: 0;
    padding: 0;
  }
  .box {
    width: 400px;
    height: 200px;
    padding: 5px;
    margin: 100px auto;
    border: 1px solid #ccc;
    overflow: auto;
  }
  .child {
    width: 200px;
    height: 400px;
    margin: 20px;
    border: 1px solid #ccc;
  }
</style>
<body>
  <div class="box">
    <div class="child">
      child
    </div>
  </div>
</body>

盒子大小

box-sizing: content-box

此时 实际宽高 = 内容区的大小(设置的width/height)+ padding + border

1. getBoundingClientRect()

获取的是在页面上实际占据的空间,不包括内部滚动条区域的大小。

width = border + padding + 内容区宽度

height = border + padding + 内容区高度 (不包括滚动隐藏起来的部分)

const boxDom = document.querySelector('.box');
const rectStyle = boxDom.getBoundingClientRect()
console.log(rectStyle.width) // 412
console.log(rectStyle.height) // 212

2. clientWidth/clientHeight

client* = padding + 内容区的大小 (不包括滚动条的大小)

const boxDom = document.querySelector('.box');
console.log(boxDom.clientWidth); // 393
console.log(boxDom.clientHeight); // 210 ---  不包括滚动条的宽度

3. scrollWidth/scrollHeight

scroll* = 内容区(包括元素滚动区) + padding

元素不滚动时,等于 client*

const boxDom = document.querySelector('.box');
console.log(boxDom.clientWidth); // 393
console.log(boxDom.clientHeight); // 452 --- child margin 20*2 + border + 1*2 + 400 + 自身 padding 5 * 2

4. offsetWidth/offsetHeight

offset* = border + padding + 内容区大小

const boxDom = document.querySelector('.box');
console.log(boxDom.clientWidth); // 412 ---  不包括滚动条的宽度
console.log(boxDom.clientHeight); // 212

box-sizing: border-box

设置 box-sizing: border-box 时:此时给盒子的 宽高 = 设置的宽高

<style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box
  }

1. getBoundingClientRect()

获取的是在页面上实际占据的空间,不包括内部滚动条区域的大小。 width = border + padding + 内容区宽度 height = border + padding + 内容区高度 (不包括滚动条的宽度)

const boxDom = document.querySelector('.box');
const rectStyle = boxDom.getBoundingClientRect()
console.log(rectStyle.width) // 400
console.log(rectStyle.height) // 200

2. clientWidth/clientHeight

client* = padding + 内容区的大小 (不包括滚动条的宽度)

const boxDom = document.querySelector('.box');
console.log(boxDom.clientWidth); // 381 --- 设置的宽 - 滚动条的宽度 - border
console.log(boxDom.clientHeight); // 198 --- 设置的宽 - border

3. scrollWidth/scrollHeight

scroll* = 内容区(包括元素滚动区) + padding

元素不滚动时,等于 client*

const boxDom = document.querySelector('.box');
console.log(boxDom.clientWidth); // 381 ---  不包括滚动条的宽度
console.log(boxDom.clientHeight); // 450 --- child margin 20*2 + 400 + 自身 padding 5 * 2

4. offsetWidth/offsetHeight

offset* = border + padding + 内容区宽度

const boxDom = document.querySelector('.box');
console.log(boxDom.clientWidth); // 400 ---  不包括滚动条的宽度
console.log(boxDom.clientHeight); // 200