通过offsetTop函数获取层叠Div的偏移量

 1 window.onload=function(){
 2     var box=document.getElementById("box");
 3     //alert(box.offsetTop);  //margin:20px;
 4     //alert(box.offsetParent.offsetTop); //box父元素的高度
 5     alert(offsetTop(box)); //运用函数
 6     }
 7 
 8     function offsetTop(element){
 9         var top=element.offsetTop;//得到第一层距离
10         var parent=element.offsetParent;//得到第一个父元素
11         while(parent !==null){  //如果还有上一层 ,不为空
12             top+=parent.offsetTop; //本层距离累加
13             parent=parent.offsetParent //得到本层的父元素
14         }                                            //继续循环
15         return top;
16     };

HTML:
	<div id="pox">
		<div id="box">测试Div</div>
		</div>

  CSS:

  

#box{
    width:200px;
    height:200px;
    background:red;
    margin:20px;
    
}
#pox{
    width:400px;
    height:400px;
    background:green;
    position:absolute;
    top:50px;
    left:50px;
}

 

 

posted @ 2015-06-10 13:19  hutaotaotao  阅读(389)  评论(0编辑  收藏  举报