JavaScript:offsetParent

说明

距离元素 最近 的一个具有 定位(position是 relative,absolute,fixed) 的 祖先元素,若祖宗都不符合条件,offsetParent为body

提示:有定位 指 position 是 relative,absolute,fixed

相关属性

offsetParent 用于 offsetLeft 和 offsetTop 属性。

几种情况

  1. 元素自身 有定位,父元素 不存在定位,则 offsetParent 的结果为null(firefox中为:body,其他浏览器返回为null)

  2. 元素自身 无定位,且父元素 存在定位,offsetParent为离自身最近且经过定位的父元素

  3. 元素自身 无定位,且父元素也 不存在定位,offsetParent 为 body 元素

  4. body 元素的offsetParent是null

代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
 <div id="test1" style="position:fixed"></div>

 <div id="test2"></div>

 <div id="div0" style="position:absolute;">
    <div id="div1" style="position:absolute;">
        <div id='test3'></div>    
    </div>    
</div>

<script>
    /*
    【1】元素自身有fixed定位,父元素不存在定位,则offsetParent的结果为null(firefox中为:body,其他浏览器返回为null)
    */
    var test1 = document.getElementById('test1');
    console.log('test1 offsetParent: ' + test1.offsetParent);
    /*
    【2】元素自身无fixed定位,且父元素也不存在定位,offsetParent为<body>元素
    */
    var test2 = document.getElementById('test2');
    console.log('test2 offsetParent: ' + test2.offsetParent);
    /*
    【3】元素自身无fixed定位,且父元素也不存在定位,offsetParent为<body>元素
    */
    var test3 = document.getElementById('test3');
    console.log('test3 offsetParent: ' + test3.offsetParent);
    /*
    【4】<body>元素的offsetParent是null
    */
     */
    console.log('body offsetParent: ' + document.body.offsetParent);//null

</script>
</body>

</html>

参考:
https://blog.csdn.net/u012532033/article/details/72851692
https://www.runoob.com/jsref/prop-element-offsetparent.html


原文出处:/show_1IX8PbFAnRvK.html