$(function () {
var maxH = 0;
$('.features').each(function () {
maxH = Math.max(maxH, $(this).height());
});
$('.features').each(function () {
$(this).height(maxH);
});
});
height 導致內容溢出或留白$(window).on('load') 執行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);
});
});
});
<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>
<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>
<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 | 固定高度易溢出 | 高 |
| Flexbox | IE10+ | 原生響應式 | 內容撐開,無溢出 | 極低 |
| CSS Grid | 現代瀏覽器 | 原生響應式 + 二維控制 | 內容撐開 | 極低 |
| display: table | IE8+ | 寬度固定時可用 | 內容撐開 | 低 |
// 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。