码迷,mamicode.com
首页 > 其他好文 > 详细

关于clientHeight,offsetHeight等小笔记

时间:2016-05-12 19:40:15      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

遇到一个有个问题:关于clientHeight,offsetHeight,scrollHeight,以及height,contentHeight(width也一样)的区别。
这里有参考http://stackoverflow.com/questions/21064101/understanding-offsetwidth-clientwidth-scrollwidth-and-height-respectively
https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth等等。
包括一些自己的理解做一下笔记(o(╯□╰)o不一定完全正确)
这里借用一下别的图:
技术分享
注意这个图中有个问题就是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;
        }

结果是这样的:
技术分享
显然,这里显示出来的内容区域变为了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);

技术分享

可以看到结果是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);

技术分享
结果是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);

技术分享

显然结果是83,而在IE11中

console.log(div1.currentStyle.height);

技术分享

结果是100。。

关于clientHeight,offsetHeight等小笔记

标签:

原文地址:http://blog.csdn.net/creasher/article/details/51353416

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!