首頁  >  問答  >  主體

css - 关于offsetLeft和offsetTop

offsetLeft不是当前元素的左外边框到包含元素的左内边框之间的像素距离吗?
为什么多出了8px

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>test2</title>
        <style media="screen">
            .cc{
                padding: 50px 30px;
            }
            .fc{
                background-color: blue;
                width:300px;
                height: 200px;
            }
        </style>
    </head>
    <body>
        <p class="cc">
            <p class="fc" >

            </p>
        </p>
    </body>
    <script type="text/javascript">
        var fc = document.querySelector('.fc');
        console.log(fc.offsetLeft+':'+fc.offsetTop);
    </script>
</html>

大家讲道理大家讲道理2742 天前969

全部回覆(2)我來回復

  • 巴扎黑

    巴扎黑2017-04-17 15:02:35

    offsetLeftoffsetTop 回傳的是相對於 offsetParent 元素的距離,而 offsetParent 指的是一個元素最近的父級定位元素,如果沒有定位元素就是文檔根節點。

    你現在輸出的值加上 body 本身有 8px 的 margin,其實是沒錯的。
    你可以加個 body { margin:0 } 或是為父級元素加上定位,輸出就是你期望的數了。

    回覆
    0
  • 迷茫

    迷茫2017-04-17 15:02:35

    預設有8px的margin。使用*{margin:0;}清除預設樣式。

    回覆
    0
  • 取消回覆