萬盛學電腦網

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

jQuery 尋找頁面最高元素:equalHeights 等高佈局實現與現代 CSS 替代

jQuery 經典實現

$(function () {
  var maxH = 0;
  $('.features').each(function () {
    maxH = Math.max(maxH, $(this).height());
  });
  $('.features').each(function () {
    $(this).height(maxH);
  });
});

缺陷分析

  • **兩次遍歷**:讀寫分離導致兩次重排
  • **破壞響應式**:固定 height 導致內容溢出或留白
  • **圖片/字體未載入時計算不準**:需在 $(window).on('load') 執行
  • **窗口 resize 不自動更新**:需綁定 resize 重算(加 throttle)

改良版:單次遍歷 + resize 監聽 + 圖片載入等待

function equalizeHeights($els) {
  // 1. 重置高度讓內容自然撐開
  $els.css('height', 'auto');

  // 2. 讀取最大高度
  var maxH = 0;
  $els.each(function () {
    maxH = Math.max(maxH, $(this).outerHeight()); // 含 padding/border
  });

  // 3. 設置統一高度
  $els.css('height', maxH);
}

$(function () {
  var $features = $('.features');
  if (!$features.length) return;

  // 等待圖片/字體載入
  var waitForImages = function ($container, cb) {
    var $imgs = $container.find('img');
    var loaded = 0;
    if ($imgs.length === 0) return cb();
    $imgs.on('load error', function () {
      if (++loaded === $imgs.length) cb();
    });
  };

  waitForImages($features.parent(), function () {
    equalizeHeights($features);

    // Resize 重算(防抖)
    var resizeTimer;
    $(window).on('resize', function () {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(function () {
        equalizeHeights($features);
      }, 150);
    });
  });
});

現代 CSS 方案:徹底拋棄 JS 計算

方案 A:Flexbox 等高(推薦,IE10+)

<div class="features-flex">
  <div class="feature">內容較少</div>
  <div class="feature">內容較多...</div>
  <div class="feature">中等內容</div>
</div>

<style>
  .features-flex { display: flex; flex-wrap: wrap; gap: 20px; }
  .feature { flex: 1 1 300px; min-width: 280px; padding: 20px; background: #fafafa; border: 1px solid #eee; }
  /* Flex 項目預設 align-items: stretch → 自動等高! */
</style>

方案 B:CSS Grid 等高(最強,現代瀏覽器)

<div class="features-grid">
  <div class="feature">...</div>
  <div class="feature">...</div>
  <div class="feature">...</div>
</div>

<style>
  .features-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
    /* Grid 單元格天然等高 */
  }
  .feature { padding: 20px; background: #fafafa; border: 1px solid #eee; }
</style>

方案 C:`display: table` 兼容 IE8+

<style>
  .features-table { display: table; width: 100%; table-layout: fixed; }
  .feature-cell { display: table-cell; vertical-align: top; padding: 20px; }
</style>

<div class="features-table">
  <div class="feature-cell">...</div>
  <div class="feature-cell">...</div>
</div>

對比總結

方案瀏覽器支援響應式內容溢出處理維護成本
jQuery 計算高度全需手動 resize固定高度易溢出高
FlexboxIE10+原生響應式內容撐開,無溢出極低
CSS Grid現代瀏覽器原生響應式 + 二維控制內容撐開極低
display: tableIE8+寬度固定時可用內容撐開低

特殊場景:內容動態增減(如 Tab 切換、AJAX 載入)

// Flex/Grid 天然適應,無需額外代碼
// 若必須用 JS(極舊瀏覽器):
function refreshEqualHeights($container) {
  $container.find('.feature').css('height', 'auto');
  equalizeHeights($container.find('.feature'));
}

// Tab 切換後調用
$('.tabs').on('click', 'button', function () {
  var $panel = $($(this).data('target'));
  $panel.siblings().hide();
  $panel.show();
  refreshEqualHeights($panel);
});

結語

**等高佈局是 CSS 的職責,不是 JS 的職責**。Flexbox/Grid 讓瀏覽器原生處理幾何計算,效能極高、零維護、完美響應式。僅在必須兼容 IE9 以下、且無法使用 Polyfill 的極端環境下,才考慮 JS 兜底。重構建議:全站搜索 .height(、outerHeight 等高邏輯,逐步遷移至 Flex/Grid。

copyright © 萬盛學電腦網 all rights reserved