DOM 基础三

来源:互联网 发布:华客数据恢复中心 编辑:程序博客网 时间:2024/06/06 21:31

元素的偏移位置

<!--             元素.offsetParent  只读 属性   返回离该元素最近的定位父级,如果没有定位父级,默认返回body            1)在IE7以下,自身有定位且没有定位父级的时候,默认是HTML            2)在IE7以下,自身没有定位且没有定位父级,但有某个父级触发了hasLayout的时候,offsetParent就会被指向到这个触发了hasLayout特性的父节点            元素.offsetLeft/offsetTop:只读 属性 返回元素的水平偏移位置/返回元素的垂直偏移位置     -->
<!DOCTYPE html><html lang="en" id="html"><head>    <meta charset="UTF-8">    <title>DOM</title>    <style type="text/css">        body{margin:0;}        #div1{width: 200px;height: 200px;background: #f00;padding:100px;margin:60px 0 0 60px;position: relative;}        #div2{width: 100px;height: 100px;background: #ff0;padding: 50px;position: relative;}        #div3{width: 100px;height: 100px;background: #ccc;position: relative;}    </style></head><body id="body">    <div id="div1">        <div id="div2">            <div id="div3"></div>        </div>    </div><script> var oDiv3=document.getElementById('div3'); // alert(document.getElementById('div2').currentStyle.hasLayout);//true // console.log(oDiv3.offsetParent.id);console.log(oDiv3.offsetLeft);//50console.log(oDiv3.offsetTop);//50</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; };
原创粉丝点击