JavaScript BOM-三剑客

元素偏移量—offset 系列

属性:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .father {
            /*position: relative;*/
            width: 200px;
            height: 200px;
            background-color: pink;
            margin: 150px;
        }

        .son {
            width: 100px;
            height: 100px;
            background-color: purple;
            margin-left: 45px;
        }

        .w {
            width: 200px;
            height: 200px;
            background-color: skyblue;
            margin: 0 auto 200px;
            padding: 10px;
            border: 15px solid red;
        }
    </style>
</head>

<body>
    <div class="father">
        <div class="son"></div>
    </div>
    <div class="w"></div>
    <script>
        // 获取元素
        var father = document.querySelector('.father');
        var son = document.querySelector('.son');


        // 1. 可以得到元素偏移量, 150 没有单位
        console.log(father.offsetTop);
        console.log(father.offsetLeft);

        console.log('-----------------------------------');
        // 2. 如果有定位的父亲,则以父亲为准,没有就以body为准
        console.log(son.offsetLeft); // 以body  195
        console.log(son.offsetLeft); // 以定位father  45

        console.log('-----------------------------------');
        // 3. offsetWidth 包含padding+border+width 只读属性不能赋值操作
        var w = document.querySelector('.w');
        console.log(w.offsetWidth); // 200 + 10 *2 + 15 * 2 = 250
        console.log(w.offsetHeight);  // 200 + 10 *2 + 15 * 2 = 250

        console.log('-----------------------------------');
        // 4. 返回带定位父亲,否则是body
        console.log(son.offsetParent); // 返回带有定位的父亲 否则返回的是body
        console.log(son.parentNode); // 返回父亲 是最近一级的父亲 亲爸爸 不管父亲有没有定位


    </script>
</body>

</html>
示例代码

offset 和 style 区别:

offset

  • 可以得到任意样式的样式值
  • 获取到的值没有单位
  • 只读属性,不能修改
  • offsetWidth offsetHeight 包含padding+border+width

style

猜你喜欢

转载自www.cnblogs.com/py-web/p/12509071.html