jQuery width()、height()

150 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      width: 100px;
      height: 100px;
      margin-top: 10px;
      border: 1px solid #000;
      background-color: pink;
    }
  </style>
  <script src="jquery-3.4.1.js"></script>
  <script>
    $(function () {
      // 获取宽度
      $('button:eq(0)').click(function () {
        // 获取到的宽度跟 margin padding border 无关
        console.log($('.box').width());
      })
      // 设置宽度
      $('button:eq(1)').click(function () {
        // $('.box').width('200px');
        $('.box').width(200); // 默认px
      })
      // 获取高度
      $('button:eq(2)').click(function () {
        // 获取到的高度跟 margin padding border 无关
        console.log($('.box').height());
      })
      // 设置高度
      $('button:eq(3)').click(function () {
        // $('.box').height('200px');
        $('.box').height(200); // 默认px
      })
    })
  </script>
</head>
<body>
  <button>获取宽度</button>
  <button>设置宽度</button>
  <button>获取高度</button>
  <button>设置高度</button>
  <div class="box"></div>
</body>
</html>
  • demo 效果: