這些高度相信很多同學都搞不清楚吧。這里我通過本地測試,發現了區別。
以聊天窗口為例。
元素(class='content')高度444px,其中上下padding分別是10px,margin為0。距離最近的一個定位的父元素的上邊距是60px。
這里,在控制台打印出各個高度值:
var c =document.getElementsByClassName('content')[0];
console.log(c.offsetTop,c.offsetHeight,c.clientHeight,c.scrollHeight,c.scrollTop);
默認情況下:
60 464 464 464 0
加了border(1px)之后
60 464 462 462 0
縮小窗口:
60 339 337 337 0
內容超出一面,出現滾動條:
60 464 464 710 246
內容超出一面,出現滾動條,且加了border(1px)之后:
60 464 462 710 246
由此可得出結論:
offsetTop
距離最近定位父元素的上外邊距(margin)。
此屬性可以獲取元素的上外緣距離最近采用定位父元素內壁的距離,如果父元素中沒有采用定位的,則是獲取上外邊緣距離文檔內壁的距離。所謂的定位就是position屬性值為relative、absolute或者fixed。
offsetHeight
是自身元素的高度(可視區):元素內容+內邊距(padding)+邊框(border),縮小瀏覽器窗口,這個值會改變
clientHeight
是自身元素的高度(可視區):元素內容+內邊距(padding),縮小瀏覽器窗口,這個值會改變
scrollHeight
= 容器元素的上下內邊距(padding)之和 + 內容所占據的寬度(含隱藏的),值最小等於元素的clientHeight屬性值。
scrollTop
= 沒有滾動條時是0。為scrollHeight - offsetHeight的差。
回到示例,想讓有消息來了,自動滾動最后一條消息,做法是:
var c =document.getElementsByClassName('content')[0];
c.scrollTop = c.scrollHeight - c.offsetHeight;
當然,這里的offsetHeight
不減去也是可以的。
其它的offsetLeft,offsetWeight,clientWidth,scrollWidth,scrollLeft同理。
jQuery里也有獲取高度的方法:
innerHeight()獲取第一個匹配元素內部區域高度(包括補白、不包括邊框)。同clientHeight
outerHeight([options])獲取第一個匹配元素外部高度(默認包括補白和邊框)。同offsetHeight
scrollTop([val]) 同scrollTop
offset()返回{left: 0, top: 60, width: 587, height: 464},對應offsetLeft,offsetTop,offsetWidth,offsetHeight
height()獲取或者設置offsetHeight
position() 獲取匹配元素相對父元素的偏移
參考:
scrollTop、offsetHeight和offsetTop等屬性用法詳解-螞蟻部落
http://www.softwhy.com/forum.php?mod=viewthread&tid=8298