offset系列属性

Tutorial: DOM实战 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0

offset 系列属性

<!DOCTYPE html>
<html lang="en">
  <head>
    <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: 20px solid red;
        /* box-sizing: border-box; */
      }
    </style>
  </head>

  <body>
    <div class="father">
      1
      <div class="son">2</div>
    </div>

    <div class="w">3</div>

    <script>
      // offset 系列
      // offsetTop offsetLeft 找到带有定位的父盒子到自己边框的距离
      // offsetWidth offsetHeight 可以得到自己的实际总尺寸
      // offsetParent 带有定位的第一个父节点
      var father = document.querySelector(".father");
      var son = document.querySelector(".son");

      // 1.可以得到元素的偏移 位置 返回的不带单位的数值
      console.log(father.offsetTop); // 150
      console.log(father.offsetLeft); // 150
      // 它以带有定位的父亲为准 如果么有父亲或者父亲没有定位 则以 body 为准
      console.log(son.offsetLeft); // 45

      var w = document.querySelector(".w");
      // 2.可以得到元素的大小 宽度和高度 是包含padding + border + width
      // 加 box-sizing: border-box  => 200 200
      // 不加
      console.log(w.offsetWidth); // 260
      console.log(w.offsetHeight); // 260

      // 3. 返回带有定位的父亲 否则返回的是body DOM元素
      // 返回带有定位的父亲 否则返回的是body
      console.log(son.offsetParent); // <div class="father">
      // 返回父亲 是最近一级的父亲 亲爸爸 不管父亲有没有定位
      console.log(son.parentNode);
    </script>
  </body>
</html>