search

Home  >  Q&A  >  body text

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>

大家讲道理大家讲道理2782 days ago989

reply all(2)I'll reply

  • 巴扎黑

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

    offsetLeft and offsetTop return the distance relative to the offsetParent element, while offsetParent refers to the nearest parent positioned element of an element. If there is no positioned element, it is the document root node.

    The value you are outputting now plus the body itself has a margin of 8px, which is actually correct.
    You can add a body { margin:0 } or add positioning to the parent element, and the output will be the number you expect.

    reply
    0
  • 迷茫

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

    There is a margin of 8px by default. Use *{margin:0;} to clear the default style.

    reply
    0
  • Cancelreply