核心需求
瀏覽器窗口調整大小時,jqGrid 表格寬度/高度自動重新計算,保持佈局協調。
方案一:簡單寬度自適應 (僅寬度)
$(function() {
$(window).on('resize', function() {
// 使用 jqGrid API 設置寬度
$('#listId').jqGrid('setGridWidth', $(window).width());
});
// 防抖優化 (推薦)
let resizeTimer;
$(window).on('resize', function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
$('#listId').jqGrid('setGridWidth', $(window).width());
}, 200);
});
});
方案二:完整寬高自適應 (含高度計算)
// 原生 JS 獲取視口尺寸 (跨瀏覽器兼容)
function getViewportSize() {
let winW, winH;
if (window.innerWidth) { // 現代瀏覽器
winW = window.innerWidth;
winH = window.innerHeight;
} else if (document.documentElement && document.documentElement.clientWidth) { // IE6 標準模式
winW = document.documentElement.clientWidth;
winH = document.documentElement.clientHeight;
} else { // 怪癖模式
winW = document.body.clientWidth;
winH = document.body.clientHeight;
}
return { width: winW, height: winH };
}
function resizeGrid() {
const size = getViewportSize();
// 預留邊距:寬度 -10,高度 -200 (根據頁面佈局調整)
$('#listId').jqGrid('setGridWidth', size.width - 10)
.jqGrid('setGridHeight', size.height - 200);
}
// 綁定 resize (防抖)
let resizeTimer;
window.onresize = function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resizeGrid, 150);
};
// 初始化調用
resizeGrid();
進階:jqGrid 內置自適應 (v4.6+)
$('#listId').jqGrid({
// ... 其他配置
autowidth: true, // 自動寬度 (父容器寬度)
shrinkToFit: true, // 列寬按比例縮放
// 注意:autowidth 不自動響應 resize,需手動觸發
});
// 手動觸發自適應
$(window).on('resize', () => {
$('#listId').jqGrid('setGridWidth', $('#gridContainer').width());
});
完整響應式佈局方案
HTML 結構
CSS 彈性佈局
.grid-container {
display: flex;
flex-direction: column;
height: 100%; /* 父容器需有確定高度 */
}
#listId {
/* jqGrid 會設置寬高 */
}
JS 智能計算
function adjustGridSize() {
const $grid = $('#listId');
const $container = $grid.closest('.grid-container');
if (!$container.length) return;
// 容器實際可用尺寸
const containerWidth = $container.width();
const containerHeight = $container.height();
// 扣除分頁器、工具欄等固定高度
const pagerHeight = $('#pager').outerHeight(true) || 0;
const toolbarHeight = $('.ui-jqgrid-titlebar').outerHeight(true) || 0;
$grid.jqGrid('setGridWidth', containerWidth);
$grid.jqGrid('setGridHeight', containerHeight - pagerHeight - toolbarHeight - 2); // -2 邊框
}
// 初始化 + resize 防抖
$(function() {
adjustGridSize();
$(window).on('resize', debounce(adjustGridSize, 200));
});
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
常見問題排查
| 現象 | 原因 | 解決 |
| 表格寬度不變 | 父容器無寬度、shrinkToFit:false | 確保父容器有寬度、啟用 shrinkToFit |
| 高度計算錯誤 | 未扣除分頁器/標題欄高度 | 動態計算 containerHeight - 固定區域高度 |
| resize 觸發過於頻繁 | 無防抖 | 添加 150-300ms 防抖 |
| 隱藏標籤頁初始化寬度 0 | 容器 display:none 時寬度為 0 | 標籤頁激活時調用 adjustGridSize() |