DOM 基础三

元素的偏移位置

<!-- 

            元素.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);//50

console.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;
 };
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值