元素的偏移位置
<!DOCTYPE html>
<html lang="en" id="html">
<head>
<meta charset="UTF-8">
<title>DOM</title>
<style type="text/css">
body{margin:0;}
#p1{width: 200px;height: 200px;background: #f00;padding:100px;margin:60px 0 0 60px;position: relative;}
#p2{width: 100px;height: 100px;background: #ff0;padding: 50px;position: relative;}
#p3{width: 100px;height: 100px;background: #ccc;position: relative;}
</style>
</head>
<body id="body">
<p id="p1">
<p id="p2">
<p id="p3"></p>
</p>
</p>
<!--
元素.offsetParent 只读 属性 返回离该元素最近的定位父级,如果没有定位父级,默认是body
1)在IE7以下,自身有定位且没有定位父级的时候,默认是HTML
2)在IE7以下,自身没有定位且没有定位父级,但有某个父级触发了hasLayout的时候,offsetParent就会被指向到这个触发了hasLayout特性的父节点
元素.offsetLeft/offsetTop:只读 属性 返回元素的水平偏移位置/返回元素的垂直偏移位置
我们再给一个元素设置定位的时候,最好也要明确其定位父级,避免兼容性的问题
-->
<script>
var oDiv3=document.getElementById('p3');
/* alert(document.getElementById('p2').currentStyle.hasLayout);//true
console.log(oDiv3.offsetParent.id);*/
console.log(oDiv3.offsetLeft);
console.log(oDiv3.offsetTop);
</script>
</body>
</html>
元素到html的绝对距离的函数的封装
function getPos(obj){
var pos={left:0,top:0};
//body的offsetParent返回值为null,条件不满足,跳出循环
while(obj){
pos.left+=obj.offsetLeft;
pos.top+=obj.offsetTop;
obj=obj.offsetParent;
}
return pos;
};