一、偏移量
1、offsetHeight
offsetHeight=元素高度+可見垂直滾動條高度+上邊框高度+下邊框高度
2、offsetWidth
offsetWidth=元素寬度+可見水平滾動條高度+上邊框寬度+下邊框寬度
3、offsetLeft
offsetLeft=元素的左外邊框至包含元素的左內邊框之間的像素距離
4、offsetTop
offsetTop=元素的上外邊框至包含元素的上內邊框之間的像素距離
以下兩個函數可以用於分別取得元素在頁面中的左和上偏移量
function getElementLeft(element){
var actualLeft=element.offsetLeft;
var current=element.offsetParent;
while(current!==null){
actualLeft+=current.offsetLeft;
current=current.offsetParent;
}
return actualLeft;
}
上偏移量類似以上代碼
二、客戶區大小
1、clientWidth
clientWidth=元素內容區寬度+左右內邊距寬度
2、clientHeight
clientHeight=元素內容區高度+上下內邊距高度
要確定瀏覽器視口大小,可以使用document.documentElement或document.body(在IE7之前的版本中)的clientWidth或clientHeight
function getViewport(){
if(document.compatMode=="BackCompat"){
return{
width:document.body.clientWidth,
height:document.body.clientHeight
};
}else{
return{
width:document.documentElement.clientWidth,
height:document.documentElement.clientHeight
};
}
}
三、滾動大小
1、scrollHeight
scrollHeight=在沒有滾動條的情況下,元素內容的總高度
2、scrollWidth
scrollWidth=在沒有滾動條的情況下,元素內容的總寬度
3、scrollLeft
scrollLeft=被隱藏在內容區域左側的像素數
4、scrollTop
crollTop=被隱藏在內容區域上方的像素數
在確定文檔的總高度時(包括基於視口的最小高度時),必須取得scrollWidth/clientWidth和scrollHeight/clientHeight中的最大值,才能保證在跨瀏覽器的環境下得到精確的結果。
var docHeight=Math.max(document.documentElement.scrollHeight,
document.documentElement.clientHeight);
var docWidth=Math.max(document.documentElement.scrollWidth,
document.documentElement.clientWidth);
四、確定元素大小
getBoundingClientRect()方法會返回一個矩形對象,包含4個屬性:left、top、right、bottom,這些屬性給出了元素在頁面中相對於視口的位置。
function getBoundingClientRect(element){
var scrollTop=documentElement.scrollTop;
var scrollLeft=documentElement.scrollLeft;
if(element.getBoundingClientRect){
if(typeof arguments.callee.offset!="number"){
var temp=document.createElement("div");
temp.style.cssText="position:absolute;left:0;top:0;";
document.body.appendChild(temp);
arguments.callee.offset=-temp.getBoundingClientRect().top-scrollTop;
document.body.removeChild(temp);
temp=null;
}
var rect=element.getBoundingClientRect();
var offset=arguments.callee.offset;
return{
left:rect.left+offset,
right:rect.right+offset,
top:rect.top+offset,
bottom:rect.bottom+offset
};
}else{
var actualLeft=getElementLeft(element);
var actualTop=getElementTop(element);
return{
left:actualLeft-scrollLeft,
right:actualLeft+element.offsetWidth-scrollLeft,
top:actualTop-scrollTop,
bottom:actualTop+element.offsetHeight-scrollTop
}
}
}
注:由於這裏使用了arguments.callee,所以這個方法不能在嚴格模式下使用。