页面内容到浏览器边距的距离

 1 <!DOCTYPE HTML>
 2 <html lang="en-US">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <div id="testID" style="width:200px;height:200px; background:#000;"></div>
 9     <script>
10     var testID = document.getElementById("testID");
11     function getXY(obj) {
12         var x = 0,
13             y = 0;
14         if (obj.getBoundingClientRect) {
15             var box = obj.getBoundingClientRect();
16             var D = document.documentElement;
17             x = box.left + Math.max(D.scrollLeft, document.body.scrollLeft) - D.clientLeft;
18             y = box.top + Math.max(D.scrollTop, document.body.scrollTop) - D.clientTop;
19         } else {
20             for (; obj != document.body; x += obj.offsetLeft, y += obj.offsetTop, obj = obj.offsetParent) {}
21         }
22         return {
23             x: x,
24             y: y
25         };
26     }
27     console.log(getXY(testID));
28     </script>
29 </body>
30 </html>
posted @ 2012-09-14 17:52  小猩猩君  阅读(431)  评论(0编辑  收藏  举报