offsetWidth、offsetHeight、clientWidth、clientHeight

1,586 阅读2分钟

概述

下面根据盒子模型来介绍一下offsetWidth、offsetHeight、clientWidth、clientHeight这四个属性。

图片.png

  • clientWidth = content-width + padding-left + padding-right - 竖向滚动条的宽度
  • clientHeight = content-height + padding-top + padding-bottom - 横向滚动条高度
  • offsetWidth = content-width + padding-left + padding-right + 左border宽度 + 右border宽度 + 竖向滚动条的宽度
  • offsetHeight = content-height + padding-top + padding-bottom + 上border宽度 + 下border宽度 + 横向向滚动条的高度

HTMLElement.offsetWidth、HTMLElement.offsetHeight

HTMLElement.offsetWidthHTMLElement.offsetHeight 都是只读属性,分别返回一个元素的布局宽度、高度。数值,没有单位。

一个典型的offsetWidth是测量包含元素的边框(border)、水平线上的内边距(padding)、竖直方向滚动条(scrollbar)(如果存在的话)、以及CSS设置的**宽度(width)**的值。

元素的offsetHeight是一种元素CSS高度的衡量标准,包括元素的边框、内边距和元素的水平滚动条(如果存在且渲染的话),不包含:before或:after等伪类元素的高度。

注:各浏览器的offsetWidth可能有所不同

这两个属性将会 round(四舍五入)为一个整数。如果你想要一个fractional(小数)值,请使用element.getBoundingClientRect().

Element.clientWidth、Element.clientHeight

HTMLElement.clientWidth, HTMLElement.clientHeight 属性表示元素的内部宽度,以像素计。该属性包括内边距 padding,但不包括边框 border、外边距 margin 和垂直滚动条(如果有的话)。数值,没有单位

滚动条

假如存在滚动条,滚动条的位置说明。

不存在padding

说明:红色(border),选中区域(content-width),此时滚动条占据了content-width的空间。 图片.png

存在padding

说明:红色(border)、选中区域(padding) 、绿色(content-width), 此时滚动条占据了padding的空间。

图片.png

总结: 滚动条是从padding开始占用空间(如果存在padding),否则是从content-width占用。如果padding的宽度不够滚动条的宽度,那么也会占用部分content-width的空间。

滚动条宽度:火狐下(16px)、chrome(17px)

例子

<style>
        #test1{
            width:200px;
            height:200px;
            padding:50px;
            border:solid 20px red;
            overflow: scroll;
            background-color: aquamarine;
        }
</style>
<div id="test1"></div>
<script type="text/javascript">
        const test1Dom = document.getElementById('test1');
        console.log('clientWidth:',test1Dom.clientWidth,'clientHeight:',test1Dom.clientHeight);
        //clientWidth = 200 + 50 + 50 - 竖向滚动条宽度(火狐16px,chrome 17px) = 284/283
        //clientHeight = 200 + 50 + 50 - 横向条高度(火狐16px,chrome 17px) = 284/283
        console.log('offsetWidth',test1Dom.offsetWidth,'offsetHeight:',test1Dom.offsetHeight);
        //offsetWidth = 200 + 50 + 50 + 20 + 20 = 340
        //offsetHeight = 200 + 50 + 50 + 20 + 20 = 340
</script>