核心 API
window.innerHeight:視口高度(含水平捲軸)。
document.documentElement.clientHeight:文檔佈局高度(不含捲軸)。
screen.height:螢幕物理解析度(不隨視窗變化)。
即時追蹤視窗高度變化
function updateHeight() {
var h = window.innerHeight;
document.getElementById('heightDisplay').textContent = h;
// 調整元素高度
document.getElementById('content').style.height = h + 'px';
}
window.addEventListener('resize', updateHeight);
updateHeight(); // 初始化
行動裝置注意
- 鍵盤彈出會觸發
resize,導致高度驟減;可用 window.visualViewport.height (Visual Viewport API) 獲取可見區域高度。
- iOS Safari 底部工具列收縮也會觸發 resize,建議用
vh 單位配合 calc(100vh - constant(safe-area-inset-bottom))。
CSS 替代方案
.full-height { height: 100vh; } /* 視口高度 */
@supports (height: 100dvh) { .full-height { height: 100dvh; } } /* 動態視口高度,支援瀏覽器 UI 縮放 */