<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <style> *{ margin:0; padding:0} div {padding: 40px 50px;} #div1 {background: red;position: relative;} #div2 {background: green; position: relative;} #div3 {background: orange; position: relative;} </style> <script> window.onload = function() { var oDiv3 = document.getElementById(‘div3‘); var p = getPos( oDiv3 ); //alert( p.left ); alert( p.top ); function getPos(obj) { var pos = {left:0, top:0};//Jason while (obj) { pos.left += obj.offsetLeft; pos.top += obj.offsetTop; obj = obj.offsetParent; } return pos; } } </script> </head> <body id="body1"> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> </body> </html>
原文:http://www.cnblogs.com/Xuman0927/p/getPos.html