1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5 <title>ll无标题文档</title> 6 <style> 7 div{padding:40px 50px;} 8 #div1{background:red;position:relative;} 9 #div2{background:green;position:relative;} 10 #div3{background:orange;position:relative;} 11 </style> 12 <script> 13 window.onload=function(){ 14 var oDiv3=document.getElementById('div3'); 15 //alert(oDiv3.offsetLeft); 16 /*var obj=oDiv3; 17 while(obj){ 18 alert(obj.id+':'+obj.offsetTop); 19 var iTop=0; 20 iTop+=obj.offsetTop; 21 obj=obj.offsetParent; 22 alert(obj+':'+obj.id); 23 24 } 25 alert(iTOP);*/ 26 var p=getPos(oDiv3); 27 alert(p.top); 28 function getPos(obj){ 29 var pos={left:0, top:0} 30 while(obj) 31 { 32 pos.left+=obj.offsetLeft; 33 pos.top+=obj.offsetTop; 34 obj=obj.offsetParent; 35 } 36 return pos; 37 } 38 39 40 41 42 }; 43 44 </script> 45 46 </head> 47 48 <body id="body1"> 49 <div id="div1"> 50 <div id="div2"> 51 <div id="div3"></div> 52 </div> 53 54 55 </div> 56 57 58 59 </body> 60 </html>