关于clientHeight,offsetHeight等小笔记

关于clientHeight,offsetHeight等小笔记

标签: 前端
  2891人阅读  评论(0)  收藏  举报
  分类:

之前遇到一个问题:关于clientHeight,offsetHeight,scrollHeight,以及height,contentHeight(width也一样)的区别。因为不太分的清,就去找了一些资料,下面是一些笔记及个人理解(o(╯□╰)o不一定完全正确,望指正) 
这里有参考http://stackoverflow.com/questions/21064101/understanding-offsetwidth-clientwidth-scrollwidth-and-height-respectively, 
https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth等等。

这里借用一下别人的图: 
这里写图片描述 
注意这个图中有个问题就是paddingBottom和paddingRight,画的不太对(个人感觉)。另外注意在chrome中paddingBottom是呈现在滚轮部分的底部的,而在别的浏览器则不是这样╮(╯_╰)╭。

这里可以看一下粗略对比: 
chrome: 
这里写图片描述 
Firefox: 
这里写图片描述

1.首先,有一点要明白,就是如果你在css中设置了height值,然后你在浏览器中调试的时候可能会发现,当你鼠标选中那个元素的时候,它的值可能不等于你之前设置的height的值。 
例如:(在chrome浏览器)

 #div1{
            width:100px;
            height:100px;
            overflow: auto;
            background-color: yellow;
            padding:10px;
            border:4px solid red;
        }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

结果是这样的: 
这里写图片描述 
显然,这里显示出来的内容区域变为了83*83。这是为什么….这个问题纠结了我好久,巴特,其实这个答案很简单╮(╯_╰)╭….. 
这是因为设置的那cssheight包括了scorll bar的宽度…..我们看见的那块内容区域: 
contentHeight = cssHeight- scorllBarHeight 
并且我们可以看出这里scorllBarHeigh=100-83=17

2.再来看clientHeight。这个其实就是可视化区域,包括content,padding但不包括border,scroll bar …他不能从css直接得到,它和scroll bar 的宽度有关 
再看刚才的那个例子,我们讲它打印出来:

console.log(div1.clientHeight);
   
   
  • 1

这里写图片描述

可以看到结果是103。 
那么它是怎么的出来的呢? 
它的计算式子可以这么写: 

clientHeight = cssHeight+ paddingTop+ paddingBottom- scrollBarWidth 

这里也就是clientWidth = 100+10+10-17=103 
嘛,根据第1点我们知道,它实际上也是 

clientWidth =contentHeight+ paddingTop+ paddingBottom 

**3.**offsetHeight的话,其实就是包括border的可视化盒子的全部高度。也就是书,包括了content,padding,scroll bar ,border。也可以说是cssHeight,padding,border。那么上面那个例子中,

 console.log(div1.offsetHeight);
   
   
  • 1

这里写图片描述 
结果是128,可以表示为 

offsetHeight=cssHeight+paddingTop+paddingBottom+borderTop +borderBottom 

这里也就是offsetHeight=100+10+10+4+4=128

**4.**scrollHeight是包含那些隐藏在滚轮以外区域的盒子内容,它和clientHeight类似只是多包涵了一些隐藏的内容区域。它是根据内容的大小来定的,不能从css中直接获得。

ps:这里有一点需要注意:在chrome中,如果js里返回一个height那么,这个height的值实际上就是content的值,也就是减去了scorll bar ,而不是之前css设置的height。 
用之前的那个例子:在chrome中

 console.log(getComputedStyle(div1).height);
   
   
  • 1

这里写图片描述

显然结果是83,而在IE11中

console.log(div1.currentStyle.height);
   
   
  • 1

这里写图片描述

结果是100。。

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值