深入理解offsetTop與offsetLeft


做為走上前端不歸路的我,以前只是認為offsetTop是元素的左邊框至包含元素offsetParent的左內邊框之間的像素距離,同理offsetRight是相對於上內邊框。那么問題來了,包含元素offsetParent究竟是誰呢?

是我太天真還是天后知后覺!

其實:

頁面中的元素的offsetLeft是離其最近的已經定位的元素,如果沒有就相對於body元素計算。例如:

<style type="text/css"> .box1{ width: 100px; height: 100px; background: red; } #box2{ width: 50px; height: 50px; background: green; margin: 0 auto; } </style>
    <div class="box1">
        <div id="box2">
            
        </div>
    </div>
    <script type="text/javascript">
    var box2 = document.getElementById('box2'); alert(box2.offsetParent.tagName);//輸出BODY
    alert(box2.offsetLeft);//輸出從33
    </script>

此時id為box2的div元素的祖先元素中沒有已經定位的元素,所以box2的offsetLeft是相對於body元素計算所得的。

下面我們將上面的代碼做如下修改

<style type="text/css"> .box1{ width: 100px; height: 100px; background: red; position:relative; } #box2{ width: 50px; height: 50px; background: green; margin: 0 auto; } </style>
    <div class="box1">
        <div id="box2">
            
        </div>
    </div>
    <script type="text/javascript">
    var box2 = document.getElementById('box2'); alert(box2.offsetParent.tagName);//輸出DIV
    alert(box2.offsetLeft);//輸出從25
    </script>

offsetTop同理。

通過查閱資料我還發現 IE6,IE7 對offsetParent解釋有BUG,當祖先元素都不是定位元素且本身是定位元素的時候返回document.documentElement,其他情況終返回document.body:

<body>
    <div id="b" style="position:relative">
        <div id="a"></div>
    </div><!-- a.offsetParent返回b -->
    <div id="d">
     <div id="c"></div>
    </div><!-- c.offsetParent返回document.body -->
    <div id="f">
        <div id="e" style="position:relative"></div>
    </div><!-- e.fsetParent返回document.body 在ie6,ie7中返回document.documentElement -->
</body>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM