offset与style的区别

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

offset 与 style 的区别

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      /* 内嵌样式 */

      .box {
        width: 200px;
        height: 200px;
        background-color: pink;
        padding: 10px;
      }
    </style>
  </head>

  <body>
    <div class="box" style="width: 200px">123</div>

    <script>
      // offset与 style的区别
      var box = document.querySelector(".box");
      console.log(box.offsetWidth); // 220
      // 只能得到行内样式表的值
      console.log(box.style.width); // "200px"

      // 只读属性, 不能修改, 只能获取
      // box.offsetWidth = '300px';

      // 可修改
      box.style.width = "500px";
    </script>
  </body>
</html>