1. 程式人生 > >offsetLeft 與 left的區別

offsetLeft 與 left的區別

str width element utf ont set ntb padding com

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #demo {
            width: 100px;
            height: 100px;
            /*position: absolute;*/
            background-color: pink;
        }

    </style>
</head>
<body>
<div id="demo" style="left:100px"></div>
</body>
</html>
<script>
    var demo = document.getElementById("demo");
    console.log(demo.offsetLeft);   //打印出來的是0
    console.log(demo.style.left);   //打印出來的是100px 

</script>

  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #father {
            width: 200px;
            height: 200px;
            margin: 100px;/*不是到margin左側的距離*/
            padding: 50px;
            border: 10px solid blue;
            position: absolute;
            background-color: pink;
        }

        #son {
            width: 50px;
            height: 50px;
            background-color: red;
        }
    </style>
</head>
<body>
<div id="father">
    <div id="son"></div>
</div>
</body>
</html>
<script>
    var son = document.getElementById("son");
    console.log(son.offsetLeft); //打印出來是 50px;
</script>

  技術分享

技術分享

offsetLeft 與 left的區別