关于offsetParent

了解offsetParent

 

1.当有定位父级时,则offsetParent是指当前元素最近的一个定位父级

 

2.在没有定位父级

1)自身没有定位的情况下,各浏览器默认的offsetParentbody

2)自身有定位的情况下,ie7ie6默认默认的offsetparenthtml

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>offsetTop</title>
    <style>
body{
    margin: 0;
    padding: 0;
}

        #div1{
            margin: auto;
             padding: 20px;
            background: blueviolet;
        }
        #div2{
            padding: 30px;
            background: yellow;
        }
        #div3{
            padding: 40px;
            background: salmon;
            position: relative;//定位
        }
    </style>
    <script>
        window.onload=function () {
            var div=document.getElementsByTagName('div');

            //div2没有定位
            alert(div[1].offsetParent.id);//myBody

            //div3有定位
            alert(div[2].offsetParent.id);//myBody     (ie6/7下为空)
            alert(div[2].offsetParent.tagName);//body (ie6/7下为  html)
        }
    </script>
</head>
<body id="myBody">
<div id="div1">
        <div id="div2">
            <div id="div3"></div>
    </div>
</div>
</body>
</html>

 

posted @ 2016-08-01 18:07  楚秦  Views(238)  Comments(0)    收藏  举报