offsetWidth、offsetHeight、clientHeight、clientWidth、scrollHeight、scrollWidth详细对比

173 阅读1分钟

offsetWidth、offsetHeight、clientHeight、clientWidth、scrollHeight、scrollWidth详细对比

代码测试

  • box-sizing:content-box

image-20221208134327166.png

  • box-sizing:border-boximage-20221208135113178.png

总结

  • offsetHeight、offsetWidth其实就是元素在屏幕上所占的实际宽高(包括border、padding)

    • 公式:offsetHeight = border + padding + content

    • box-sizing:content-box

      • offsetHeight = 2+10+100 = 112
    • box-sizing:border-box

      • offsetHeight = 2+10+88= 100
  • clientHeight、clientWidth是 padding+conent-滚动条宽度,就拿上述例子来说

    • 公式:clientHeight = padding + conent - 滚动条宽度

    • box-sizing:content-box

      • content高度就是我们设置的宽高,都是100
      • clientHeight = 10+100-17 = 93
    • box-sizing:border-box时,

      • content高度是我们设置的宽高 - padding - border = 100 - 10 - 2 = 88
      • clientHeight = 10+88-17 = 81
  • scrollHeight、scrollWidth是 padding + 实际内容尺寸

    • 出现滚动条时,实际内容尺寸,就是假设没有滚动条,把内容全部铺开的尺寸(注意这里是实际占屏幕的尺寸),这个例子里就是inner元素的尺寸了

    • 公式:scrollHeight = padding + 实际内容尺寸

      • box-sizing:content-box

        • scrollHeight = 10+200 = 210
      • box-sizing:border-box

        • scrollHeight = 10+200= 210

The end.