鍍金池/ 問(wèn)答/HTML/ offsetTop 和 offsetLeft 直接相對(duì)于body取值?

offsetTop 和 offsetLeft 直接相對(duì)于body取值?

書(shū)上說(shuō)Element.offsetTop 和Element.offsetLeft的偏移量是相對(duì)與父級(jí)元素的內(nèi)邊框取值,offsetTop是子元素的外邊框到父級(jí)元素內(nèi)邊框的距離。但在測(cè)試時(shí)發(fā)現(xiàn)直接就相對(duì)于body取值了,迷惑中。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
       
        .parent {
            padding: 100px;
            border: 5px solid green;
            width: 500px;
            height: 500px;
        }
        .child {
            border: 2px dashed red;
            width: 200px;
            height: 100px;
            background-color: yellow;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child"></div>
    </div>

    <script type="text/javascript">
            var parent = document.querySelector("div.parent");
            var child = document.querySelector("div.child");
    
            document.writeln("子框的偏移量比:"+child.offsetLeft+":"+child.offsetTop);
    </script> 
</body>
</html>

結(jié)果輸出:子框的偏移量比:113:113
剛好時(shí)div.parent的padding+border+body的瀏覽器默認(rèn)padding 8px,即100+5+8=113.

console.log(child.offsetParent == parent.offsetParent);

輸出結(jié)果:true.

div.child的偏移量父級(jí)child.offsetParent 應(yīng)該是div.parent吧?

回答
編輯回答
懶豬

圖片描述

2017年12月1日 07:36
編輯回答
拼未來(lái)

這個(gè)相對(duì)是相對(duì)于上層中最接近的一個(gè)定位元素.

定位元素是指 position 值非 static 的元素.

你通過(guò) css 給 div.parent 設(shè)置 position: relative. div.child 的 offsetParent 此時(shí)就是 div.parent 了.

2018年6月29日 07:08