scrollTop设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离
offsetTop获取对象相对于版面或由offsetTop属性指定的父坐标的计算顶端位置
offsetLeft:获取对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置
IE67和FF的offsetTop解释结果不同,FF下其offsetParent为body,IE67下其offsetParent为父级元素。
即:elem.offsetTop=elem.offsetTop+elemFather.offsetTop+elemFatherFather.offsetTop......
兼容性写法:
function getOffset(el){
var _t =el.offsetTop;
while(el = el.offsetParent){
_t += el.offsetTop;
}
return _t;
}
while(el = el.offsetParent)
如果 el.offsetParent 存在,则加上他的offsetTop,一直循环,直到没有offsetParent;下面是个测试的例子:
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>offsetTop,offsetParent</title>
6 <style type="text/css">
7 *{ margin:0; padding:0;}
8 div{width:400px;margin-top:20px; background-color:#000; height:300px; overflow:hidden}
9 p{ margin-top:30px; background-color:#F00; height:200px; overflow:hidden}
10 a{display:block; margin-top:100px; background-color:#fff; height:20px;}
11 </style>
12 </head>
13
14 <body id="the_body">
15 <div id="the_div">
16 <p id="the_p">
17 <a href="#" id="the_a">offsetTop</a>
18 </p>
19 </div>
20 <script type="text/javascript">
21 function getOffset(el){
22 var _t =el.offsetTop;
23 var n=0;
24 while(el = el.offsetParent){
25 _t += el.offsetTop;
26 n++;
27 alert('我有'+n+'个offsetParent')
28 }
29 return _t;
30 }
31 alert(getOffset(document.getElementById('the_a')));
32 alert(document.getElementById('the_a').offsetTop); //IE67下 结果为100,没有加上父级的offsetTop
33 </script>
34
35 </body>
36 </html>