一、偏移量
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,所以这个方法不能在严格模式下使用。