1. top
此屬性僅僅在對象的定位(position)屬性被設置時可用。否則,此屬性設置會被忽略。
<div style="background-color:red; position:absolute; width:100px; height:100px;">
<p style="background-color:silver; position:absolute; top:-5px;">測試top</p>
</div>
上面是一個段落P包含在一個DIV內,可以看到P的top設置為-5px后,它的上邊距超過了容器DIV的上邊距,超過的這段距離就是設置的5px。
需要注意的是,DIV和P這一對包含元素,都需要設置position為absolute才能得到想要的結果,假如父元素不設置,則子元素的參照將是更上層定義過position的元素,直到整個文檔;
2. posTop
posTop的數值其實和top是一樣的,但區別在于,top固定了元素單位為px,而posTop只是一個數值(這一點可以通過alert("top="+id.style.top)和alert("posTop="+id.style.posTop)來證明),因此一般使用posTop來進行運算。
<div style="background-color:red; position:absolute; width:100px; height:100px;">
<p id="test" style="background-color:silver; position:absolute;">測試posTop</p>
</div>
<script>
test.style.posTop = 15+8;
alert("top="+test.style.top);
alert("posTop="+test.style.posTop);
</script>
無論你使用top或posTop來賦值,最后的結果都是一致的
3. scrollTop
<div id="container" style="background-color:silver; width:100px; height:100px; overflow:auto;">
<p style="background-color:red;">
別再做情人 做只貓 做只狗 不做情人 做只寵物至少可愛迷人 和你相交不淺無謂明日會被你憎</p>
</div>
<script>
container.scrollTop = 12;
</script>
這一段文本在這個100*100的DIV內無法完全顯示,所以設置了overflow為auto,它會出現一個上下方向的滑動框,假如沒有設置id.scrollTop屬性的話,默認情況下滑塊位置在頂端。而設置了scrollTop值為12后,滑塊的位置改變了,默認顯示是卷過了12個象素的文本。如果設置overflow為hidden,則將會無法顯示頂部12個象素的文本。
注意設置方式是id.scrollTop,而不是id.style.scrollTop。
4. scrollHeight 與 offsetHeight
offsetHeight是自身元素的高度,scrollHeight是 自身元素的高度+隱藏元素的高度。
<div id="container" style="background-color:silver; width:100px; height:100px; overflow:auto;">
<p style="background-color:red; height:250px; ">
別再做情人 做只貓 做只狗 不做情人 做只寵物至少可愛迷人 和你相交不淺無謂明日會被你憎</p>
</div>
<script>
alert(container.offsetHeight);
alert(container.scrollHeight);
</script>
將依次輸出100,250。因為已經指定了元素的height為100px,所以offsetHeight始終為100px;內部元素為250px,而容器元素只有100px,那么還有150px的內容它無法顯示出來,但它卻是實際存在的,所以scrollHeight值為100+150=250。