後台管理系統常見版面:頂部標題列、工具列、雙表格區塊。需隨瀏覽器視窗大小自動調整兩個表格容器高度,並支援螢幕解析度自動計算分頁筆數。
function com_onresize() {
// 取得各區塊高度
var contentsHeight = document.body.clientHeight; // 可視區高度
var buttonsHeight = document.getElementById("buttons").offsetHeight; // 底部工具列
var head1Height = document.getElementById("head1").offsetHeight; // 標題列 1
var head2Height = document.getElementById("head2").offsetHeight; // 標題列 2
// 計算可用高度(扣除固定區塊與間距 13px)
var h = contentsHeight - buttonsHeight - head1Height - head2Height - 13;
// 最小高度保護
if (h < 110) return;
// 平均分配給兩個表格容器
document.getElementById("TableContainer1").style.height = (h / 2) + 'px';
document.getElementById("TableContainer2").style.height = (h / 2) + 'px';
}
// 綁定視窗調整事件
window.onresize = com_onresize;
// 初始化執行一次
window.onload = com_onresize;
function com_sbs_pagesize() {
var screenHeight = window.screen.height; // 螢幕總高度
var availHeight = window.screen.availHeight; // 可用工作區高度(扣除工作列)
// 取得表格目前行數(假設 TableContainer1 內第一個 table)
var index = document.getElementById("TableContainer1").children[0].rows.length;
var buttonsHeight = document.getElementById("buttons").offsetHeight;
var head1Height = document.getElementById("head1").offsetHeight;
var head2Height = document.getElementById("head2").offsetHeight;
// 固定區塊總高度
var mainH = buttonsHeight + head1Height + head2Height + 13;
// 每列預估高度:20(scroll) + 35(title) + 25(tr) = 80px
// while 迴圈遞減行數直到符合螢幕高度
while ((availHeight - mainH) < (20 + 35 + 25 * index) * 2) {
index = index - 1;
}
var tableHeight = 20 + 35 + 25 * index;
// 套用高度
document.getElementById("TableContainer1").style.height = tableHeight + 'px';
document.getElementById("TableContainer2").style.height = tableHeight + 'px';
// 調整視窗大小配合內容(謹慎使用,可能干擾使用者)
window.resizeTo(document.body.offsetWidth, mainH + tableHeight * 2);
}
| 屬性 | 說明 | 含邊框/捲軸 |
|---|---|---|
clientHeight | 可視區高度(含 padding,不含 border/scrollbar) | 無 |
offsetHeight | 元素完整高度(含 padding + border + scrollbar) | 有 |
scrollHeight | 內容完整高度(含被捲軸隱藏部分) | 有 |
window.screen.height | 螢幕物理解析度高度 | — |
window.screen.availHeight | 螢幕可用工作區高度(扣除作業系統工作列) | — |
.layout {
display: flex;
flex-direction: column;
height: 100vh; /* 佔滿視窗高度 */
}
.header { flex: 0 0 auto; } /* 固定高度 */
.toolbar { flex: 0 0 auto; } /* 固定高度 */
.table-container {
flex: 1 1 auto; /* 平均分配剩餘空間 */
min-height: 110px; /* 最小高度保護 */
overflow: auto; /* 內容超出時捲動 */
}
純 CSS 解決方案:無需 JS 監聽 resize、效能更好、無閃爍。
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
if (entry.target.id === 'tableContainer') {
// 容器尺寸變更時的邏輯
console.log('容器高度:', entry.contentRect.height);
}
}
});
resizeObserver.observe(document.getElementById('tableContainer'));
:root {
--header-height: 60px;
--toolbar-height: 40px;
}
.table-container {
height: calc(100vh - var(--header-height) - var(--toolbar-height) - 13px);
}
傳統 JS 計算高度方案在舊專案常見,但現代 CSS (Flexbox/Grid、vh、calc()、CSS 變數) 已能完美替代大部分場景,減少 JS 邏輯、提升效能與維護性。新專案優先採用 CSS 方案,僅在極度複雜的動態計算需求下使用 JS 輔助。