關於clientHeight,offsetHeight等小筆記

之前遇到一個問題:關於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;
        }

結果是這樣的:
這裏寫圖片描述
顯然,這裏顯示出來的內容區域變爲了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。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章