偏移量 offsetLeft & offsetTop

内外边距一定要初始化,不然有些浏览器下取值要悲剧了

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 2 <html xmlns="http://www.w3.org/1999/xhtml">

 3 <head>

 4     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

 5     <title>111</title>

 6     <style type="text/css">

 7     body{

 8         margin: 0;

 9         padding: 0;

10     }

11     </style>

12 </head>

13 <body>

14     <div id="out1" style="width:200px;height:100px;overflow:scroll; margin:88px;">

15         <div style="background:#666666;height:150px;"></div>

16     </div>

17     <script type="text/javascript" src="test12.js"></script>

18 </body>

19 </html>
 1 function getElementLeft(element) {

 2     var actualLeft = element.offsetLeft;

 3     var current = element.offsetParent;

 4 

 5     while (current !== null) {

 6         actualLeft += current.offsetLeft;

 7         current = current.offsetParent;

 8     }

 9     return actualLeft;

10 }

11 

12 function getElementTop(element) {

13     var actualTop = element.offsetTop;

14     var current = element.offsetParent;

15 

16     while (current !== null) {

17         actualTop += current.offsetTop;

18         current = current.offsetParent;

19     }

20     return actualTop;

21 }

22 

23 var div = document.getElementById("out1");

24 console.log(getElementLeft(div));

25 console.log(getElementTop(div));

你可能感兴趣的:(left)