萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery outerWidth/outerHeight 詳解:獲取含 margin/border/padding 的完整元素尺寸

方法定位

.outerWidth() / .outerHeight() 獲取元素完整佈局尺寸,可選是否包含 margin。是佈局計算、碰撞檢測、定位對齊的關鍵工具。

語法與參數


// 獲取
.outerWidth([includeMargin])  // Boolean,默認 false
.outerHeight([includeMargin])

// 返回值:數值(像素),無單位
// includeMargin=true 時:content + padding + border + margin
// includeMargin=false(默認):content + padding + border

盒模型尺寸層級圖解

┌─────────────────────────────────────┐
│              margin                 │  ← outerWidth(true) / outerHeight(true)
├─────────────────────────────────────┤
│            border                   │
├─────────────────────────────────────┤
│            padding                  │  ← innerWidth() / innerHeight()
├─────────────────────────────────────┤
│           content (width/height)    │  ← .width() / .height()
└─────────────────────────────────────┘

完整可運行範例

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>outerWidth/outerHeight 示例</title>
  <style>
    #box {
      width: 300px; height: 100px;
      padding: 10px; margin: 15px;
      border: 2px solid #3498db;
      background: #ecf0f1;
    }
    .info { font-family: monospace; background: #f8f9fa; padding: 10px; margin-top: 10px; }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="box">內容區 300×100</div>
  <button id="btn-dim">顯示各層級尺寸</button>
  <div id="output" class="info"></div>

  <script>
    $('#btn-dim').click(function() {
      const $box = $('#box');
      const txt = `
        width(): ${$box.width()}          (content)
        height(): ${$box.height()}
        innerWidth(): ${$box.innerWidth()}    (content + padding)
        innerHeight(): ${$box.innerHeight()}
        outerWidth(): ${$box.outerWidth()}    (content + padding + border)
        outerHeight(): ${$box.outerHeight()}
        outerWidth(true): ${$box.outerWidth(true)}  (+ margin)
        outerHeight(true): ${$box.outerHeight(true)}
      `;
      $('#output').text(txt.trim());
    });
  </script>
</body>
</html>

輸出示例

width(): 300          (content)
height(): 100
innerWidth(): 320     (content + padding*2)
innerHeight(): 120
outerWidth(): 324     (content + padding*2 + border*2)
outerHeight(): 124
outerWidth(true): 354 (+ margin*2)
outerHeight(true): 154

進階應用場景

1. 精確定位:彈窗/提示框對齊元素邊緣


function positionTooltip($trigger, $tooltip) {
  const offset = $trigger.offset();
  const triggerW = $trigger.outerWidth();
  const triggerH = $trigger.outerHeight();
  const tipW = $tooltip.outerWidth();
  const tipH = $tooltip.outerHeight();
  
  $tooltip.css({
    left: offset.left + (triggerW - tipW) / 2,
    top: offset.top - tipH - 8 // 箭頭間距
  });
}

2. 碰撞檢測/拖拽邊界限制


function clampInContainer($el, $container) {
  const cRect = $container[0].getBoundingClientRect();
  const eRect = $el[0].getBoundingClientRect();
  const maxX = cRect.width - $el.outerWidth();
  const maxY = cRect.height - $el.outerHeight();
  
  $el.css({
    left: Math.max(0, Math.min(maxX, eRect.left - cRect.left)),
    top: Math.max(0, Math.min(maxY, eRect.top - cRect.top))
  });
}

3. 等寬/等高佈局計算


function equalizeOuterHeight($items) {
  const maxH = Math.max(...$items.map((i, el) => $(el).outerHeight(true)).get());
  $items.outerHeight(maxH); // 注意:outerHeight 不支持設置,需手動計算 content 高度
  // 正確做法:
  $items.each(function() {
    const $el = $(this);
    const targetContentH = maxH 
      - (parseFloat($el.css('paddingTop')) || 0)
      - (parseFloat($el.css('paddingBottom')) || 0)
      - (parseFloat($el.css('borderTopWidth')) || 0)
      - (parseFloat($el.css('borderBottomWidth')) || 0)
      - (parseFloat($el.css('marginTop')) || 0)
      - (parseFloat($el.css('marginBottom')) || 0);
    $el.height(Math.max(0, targetContentH));
  });
}

4. 表格列寬自適應


function autoFitColumns($table) {
  $table.find('th').each(function(i) {
    const maxW = Math.max(
      $(this).outerWidth(),
      ...$table.find('tbody tr').map((_, row) => $(row).find('td').eq(i).outerWidth()).get()
    );
    $(this).width(maxW); // 設置內容寬度
    $table.find('tbody td').eq(i).width(maxW);
  });
}

常見坑點

問題原因解決
返回 0 元素或祖先 display:none 臨時顯示測量或用 getBoundingClientRect()
無法設置 .outerWidth(300) jQuery 不支持設置 outerWidth/Height 手動計算 content 尺寸後用 .width()/height() 設置
inline 元素測量不準 inline 元素無寬高、margin 垂直無效 設置 display:inline-block 或 block
box-sizing 影響計算 jQuery 總按 content-box 計算,CSS 可能 border-box 統一用 box-sizing:border-box 並用 outerWidth(true) 佈局
transform:scale 後尺寸失真 jQuery 返回佈局尺寸,非視覺渲染尺寸 用 getBoundingClientRect() 獲取渲染後尺寸

原生替代:getBoundingClientRect()


const rect = element.getBoundingClientRect();
// rect.width / height 已含 padding + border,且為渲染後實際像素(含 transform 縮放)
// 精確到小數,性能極高,無 jQuery 依賴
// 需 margin 時:手動 getComputedStyle 解析 margin 值相加

總結

  • .outerWidth()/outerHeight() 獲取 content+padding+border;傳 true 含 margin。
  • 唯讀,不可直接設置;需反推 content 尺寸後用 .width()/height() 設置。
  • 佈局計算、定位、碰撞檢測、等高佈局的核心數據來源。
  • 現代項目優先 getBoundingClientRect()(含 transform、高精度、無依賴)。
  • 理解盒模型層級,配合 box-sizing:border-box 統一尺寸語義,能避開 90% 佈局坑。
copyright © 萬盛學電腦網 all rights reserved