css - 关于offsetLeft和offsetTop
大家讲道理
大家讲道理 2017-04-17 15:00:35
0
2
1011

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>

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
巴扎黑

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.

迷茫

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template