javascript Dom中offset和client获取元素高、宽和获取距离各元素之间距离问题

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }
    body {
      padding: 20px;
      border: 20px solid blue;
    }
    .box1 {
      width: 200px;
      height: 200px;
      background-color: pink;
      padding: 20px;
      border: 20px solid red;
      margin: 20px;
    }
    .box2 {
      position: relative;
      width: 200px;
      height: 200px;
      background-color: pink;
      padding: 20px;
      border: 20px solid red;
      margin: 20px;
    }
    .box3 {
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: aqua;
      margin: 20px;
      padding: 20px;
      border: 10px solid black;
    }

  </style>
</head>
<body>
  <div class="box1"></div>


  <div class="box2">
    <div class="box3"></div>
  </div>
  <script>
    var box1 = document.querySelector(".box1");
    console.log(box1.offsetWidth);    //280px   content + padding + border
    console.log(box1.offsetHeight); //280px   content + padding + border

    console.log(box1.clientHeight);  //240px   content + padding
    console.log(box1.clientWidth);   //240px   content + padding

    console.log(box1.offsetTop);  // 60px  单个盒子下,盒子外边框相对于body外边框的大小
    console.log(box1.offsetLeft);  //60px  单个盒子下,盒子外边框相对于body外边框的大小

    console.log(box1.clientTop);  // 20px box1的上边框大小
    console.log(box1.clientLeft);  // 20px box1的左边框大小

    console.log("--------------------------");

    var box2 = document.querySelector(".box2");
    var box3 = document.querySelector(".box3");
    console.log(box3.offsetWidth);    //160px   content + padding + border
    console.log(box3.offsetHeight); //160px   content + padding + border

    console.log(box3.clientHeight);  //140px   content + padding
    console.log(box3.clientWidth);   //140px   content + padding

    console.log(box3.offsetTop);  // 40px  嵌套盒子(父盒子)下且有定位,相对于外盒子内边框的大小
    console.log(box3.offsetLeft);  //40px  嵌套盒子(父盒子)下且有定位,相对于外盒子内边框的大小

    console.log(box3.clientTop);  // 10px   box3的上边框大小
    console.log(box3.clientLeft);  // 10px  box3的左边框大小


  </script>
</body>
</html>

javascript Dom中offset和client获取元素高、宽和获取距离各元素之间距离问题
javascript Dom中offset和client获取元素高、宽和获取距离各元素之间距离问题

javascript Dom中offset和client获取元素高、宽和获取距离各元素之间距离问题
javascript Dom中offset和client获取元素高、宽和获取距离各元素之间距离问题

上一篇:10.26HTML笔记


下一篇:CSS的相对定位详解