window.onresize 事件在瀏覽器視窗尺寸改變時觸發,是實現響應式佈局、動態圖表重繪、全螢幕組件調整的核心鉤子。本文系統整理事件特性、跨瀏覽器尺寸獲取、防抖/節流最佳實踐、常見坑點與現代替代方案。
// 傳統寫法
window.onresize = function () {
console.log('視窗大小變了');
};
// 現代推薦:addEventListener(可掛載多個監聽器)
window.addEventListener('resize', handleResize);
不同瀏覽器、文件模式(Quirks vs Standards)下尺寸屬性表現不一,建議封裝統一取值函式:
function getViewportSize() {
// 現代瀏覽器(IE9+)優先使用 innerWidth/innerHeight
if (typeof window.innerWidth === 'number') {
return { width: window.innerWidth, height: window.innerHeight };
}
// IE8- 標準模式
if (document.documentElement && document.documentElement.clientWidth) {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight
};
}
// Quirks 模式
return {
width: document.body.clientWidth,
height: document.body.clientHeight
};
}
// 使用範例
window.addEventListener('resize', () => {
const { width, height } = getViewportSize();
document.body.style.width = width + 'px';
document.body.style.height = height + 'px';
console.log(`Viewport: ${width} x ${height}`);
});
resize 事件在拖曳視窗邊緣時每秒可觸發數百次,直接執行重繪邏輯會嚴重卡頓。必須加上防抖或節流:
function debounce(fn, delay = 150) {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const debouncedResize = debounce(() => {
// 重新計算佈局、重繪圖表等高成本操作
console.log('防抖執行', getViewportSize());
}, 200);
window.addEventListener('resize', debouncedResize);
function throttle(fn, interval = 100) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= interval) {
last = now;
fn.apply(this, args);
}
};
}
const throttledResize = throttle(() => {
// 即時顯示尺寸提示等低成本操作
console.log('節流執行', getViewportSize());
}, 100);
window.addEventListener('resize', throttledResize);
| 問題 | 原因 | 解決 |
|---|---|---|
| 手機鍵盤彈出觸發 resize | 視口高度變化 | 檢查 window.visualViewport (Visual Viewport API) 或比對 document.activeElement |
| iframe 內 resize 不觸發父頁面 | 事件不冒泡 | 在 iframe 內監聽並 parent.postMessage 通知 |
| 初始化時誤觸發 | 頁面載入過程中尺寸變化 | 載入完成後再綁定,或用 requestAnimationFrame 延遲首次檢查 |
| 多監聽器互相干擾 | 共用全域變數 | 封裝為獨立模組,內部狀態私有化 |
針對元素級別尺寸變化監測(而非整個視窗),ResizeObserver 是更精準、效能更好的選擇(支援度:Chrome 64+, Firefox 69+, Safari 13.1+, Edge 79+):
const ro = new ResizeObserver(entries => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
console.log('元素尺寸變化:', width, height);
// 更新圖表、重排佈局等
}
});
ro.observe(document.querySelector('.chart-container'));
// ro.unobserve(target) / ro.disconnect() 釋放
onresize 是響應式開發的基石,但直接綁定高成本邏輯是效能大忌。請記住三原則:統一尺寸獲取、必加防抖/節流、優先考慮 ResizeObserver。將這些模式封裝成專案共用的 Hook(如 useWindowSize、useResizeObserver),即可在 Vue/React/Svelte 等框架中優雅複用。