1Window.onload=function () {2 varBox=document.getelementbyid ("Box");3 //alert (box.offsettop); //margin:20px;4 //alert (BOX.OFFSETPARENT.OFFSETTOP);//the height of the box parent element5Alert (OffsetTop (box));//using Functions6 }7 8 function OffsetTop (element) {9 varTop=element.offsettop;//get the first layer of distanceTen varParent=element.offsetparent;//get the first parent element One while(Parent!==NULL){//If there is a previous layer, it is not empty ATop+=parent.offsettop;//the distance of the layer is accumulated -Parent=parent.offsetparent//get the parent element of this layer -}//Continue looping the returntop; -};
Html:
<div id= "pox" ><div id= "box" > Test 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;}
Get the offset of a cascading div by using the offsettop function