CSS面试题:offsetHeight scrollHeight clientHeight区别

44 阅读1分钟

前置知识:盒子模型

  • box-sizing: border-box

实际宽度 = width = content + padding + border

代码:此时为border-box

#container{
  width: 300px;
  height: 200px;
  padding: 20px;
  margin: 30px;
  border:5px solid #ccc;
  box-sizing: border-box;
  overflow: auto;
  background-color: #fff;
}

image.png

内容宽度为250x150

  • box-sizing: content-box

实际宽度 = width + padding + border

代码:此时为content-box

  #container {
    width: 300px;
    height: 200px;
    padding: 20px;
    margin: 30px;
    border: 5px solid #ccc;
    /* box-sizing: border-box; */
    overflow: auto;
    background-color: #fff;
  }

image.png

内容宽度为witdh 300x200

计算规则

  • offsetHeight offsetWidth : border + padding + content
  • clientHeight clientWidth: padding + content
  • scrollHeight scrollWidth: padding + 实际内容尺寸

border-box 下情况

image.png

content-box 下情况

image.png

测试一下特别的scrollHeight 和 scrollWidth

改变代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        padding: 0;
        margin: 0;
      }
      body {
        background-color: #f1f1f1;
      }
      #container {
        width: 300px;
        height: 200px;
        padding: 20px;
        margin: 30px;
        border: 5px solid #ccc;
        box-sizing: border-box;
        overflow: auto;
        background-color: #fff;
      }
      #content {
        width: 600px;
        height: 500px;
        background-color: #f1f1f1;
        display: inline-block;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <div id="content">
      <p> offsetHeight scrollHeight clientHeight区别</p>
    </div>
    </div>
    <script>
      const container = document.getElementById('container')
      console.log('offsetHeight: ', container.offsetHeight)
      console.log('offsetWidth: ', container.offsetWidth)
      console.log('clientHeight: ', container.clientHeight)
      console.log('clientWidth: ', container.clientWidth)
      console.log('scrollHeight: ', container.scrollHeight)
      console.log('scrollWidth: ', container.scrollWidth)
    </script>
  </body>
</html>

container的子元素比自身要大,内部变成可拖动区域,子元素大小为600x500

image.png

此时:

image.png

scrollHeight = 500px + padding(20px)*2 = 540px

scrollWidth = 600px + padding(20px)*2 = 640px

补充 scrollTop 和 scrollLeft

分别指可拖动区域被隐藏部分距离顶部和左边的距离。