元素大小

一、偏移量

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值