核心代碼
function resizeElements() {
var height = document.body.clientHeight;
var targetHeight = (height - 20) + 'px';
['vivS', 'emd', 'ob'].forEach(function(id) {
var el = document.getElementById(id);
if (el) el.style.height = targetHeight;
});
}
window.onload = resizeElements;
window.onresize = resizeElements;
關鍵點
clientHeight 獲取視口/body 可見高度(不含滾動條)
- 統一處理函數避免代碼重複
- 減去 20px 可能為頂部導航/邊距預留
- 同時綁定
onload(初始化)與 onresize(窗口變化)
現代改進:CSS 方案優先
/* 視口單位方案 */
#vivS, #emd, #ob { height: calc(100vh - 20px); }
/* Flex 佈局方案 */
.container { display: flex; flex-direction: column; height: 100vh; }
.content { flex: 1; overflow: auto; }
- CSS 方案無 JS 依賴、無閃爍、性能更優
- JS 方案適用於複雜計算邏輯或需兼容極舊瀏覽器
resize 事件建議防抖(setTimeout/requestAnimationFrame)