offsetTop/offsetHeight scrollTop/scrollHeight 這幾個屬性困擾了我N久,這次一定要搞定。
假設 obj 為某個 HTML 控件。
obj.offsetTop obj距離上方或上層控件的位置,整型,單位像素。
obj.offsetHeight obj自身的高度,整型,單位像素。
offsetTop 可以獲得 HTML 元素距離上方或外層元素的位置,style.top 也是可以的,二者的區別是:
一、offsetTop 返回的是數字,而 style.top 返回的是字符串,除了數字外還帶有單位:px。
二、offsetTop 只讀,而 style.top 可讀寫。
三、如果沒有給 HTML 元素指定過 top 樣式,則 style.top 返回的是空字符串。
scrollTop 是“卷”起來的高度值,示例:
<div style="width:100px;height:100px;overflow:hidden;" id="p">
<div style="width:50px;height:300px;" id="t">如果為 p 設置了 scrollTop,這些內容可能不會完全顯示。</div>
</div>
<script type="text/javascript">
var p = document.getElementById("p");
p.scrollTop = 10;
</script>
由於為外層元素 p 設置了 scrollTop,所以內層元素會向上卷。
scrollHeight 與 offsetHeight
offsetHeight是自身元素的高度,scrollHeight是 自身元素的高度+隱藏元素的高度(是不是可以理解成內層元素的offsetHeight值???)。
<div id="container" style=" width:100px; height:100px; overflow:auto;">
<p style=" height:250px; ">
別再做情人 做只貓 做只狗 不做情人 做只寵物至少可愛迷人 和你相交不淺無謂明日會被你憎
</p>
</div>
<script>
alert(document.getElementById("container").offsetHeight);
alert(document.getElementById("container").scrollHeight);
</script>
將依次輸出100,250。因為已經指定了元素的height為100px,所以offsetHeight始終為100px;內部元素為 250px,而容器元素只有100px,那么還有150px的內容它無法顯示出來,但它卻是實際存在的,所以scrollHeight值為 100+150=250。
轉:http://hi.baidu.com/lampers/item/1605adc13daa00350931c6fc
http://www.cnblogs.com/fullhouse/archive/2012/01/16/2324131.html

alert("網頁可見區域寬:" + 'document.body.clientWidth.'+document.body.clientWidth); alert("網頁可見區域高:" + 'document.body.clientHeight.'+document.body.clientHeight); alert("網頁可見區域高 (包括邊線的寬):" + 'document.body.offsetWidth.'+document.body.offsetWidth); alert("網頁可見區域高 (包括邊線的高):" + 'document.body.offsetHeight.'+document.body.offsetHeight); alert("網頁正文全文寬:" + 'document.body.scrollWidth.'+document.body.scrollWidth); alert("網頁正文全文高:" + 'document.body.scrollHeight.'+document.body.scrollHeight); alert("網頁被卷去的高:" + 'document.body.scrollTop.'+document.body.scrollTop); alert("網頁被卷去的左:" + 'document.body.scrollLeft.'+document.body.scrollLeft); alert("網頁正文部分上:" + "window.screenTop."+window.screenTop); alert("網頁正文部分左:" + "window.screenLeft."+window.screenLeft); alert("屏幕分辨率的高:" + "window.screen.height."+window.screen.height); alert("屏幕分辨率的寬:" + "window.screen.width."+window.screen.width); alert("屏幕可用工作區高度:" + "window.screen.availHeight."+window.screen.availHeight); alert("屏幕可用工作區寬度:" + "window.screen.availWidth." +window.screen.availWidth);