onload 僅處理初始載入,無法應對 JS 動態操作 DOM 導致的高度變化document.body.scrollHeightbody.scrollHeight 與 documentElement.scrollHeight 表現不一<iframe id="frame_content" src="page.html" scrolling="no" frameborder="0" onload="this.height=100"></iframe>
<script>
function reinitIframe() {
var iframe = document.getElementById("frame_content");
try {
var bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
var height = Math.max(bHeight, dHeight); // 兼容各瀏覽器
iframe.height = height;
} catch (ex) {
// 跨域異常靜默處理
}
}
// 200ms 輪詢,效能影響極小
window.setInterval("reinitIframe()", 200);
</script>
| 技術點 | 說明 |
|---|---|
| onload 預縮 | onload="this.height=100" 先縮小容器,解決「長高不縮回」問題 |
| 雙重 scrollHeight 取最大值 | 兼容 IE/FF/Chrome/Safari/Opera 在 absolute/float 布局下的差異 |
| try-catch 跨域保護 | 同域下正常工作,跨域靜默失效不報錯 |
| 200ms 輪詢 | 測試 5 瀏覽器同時運行 CPU 佔用近 0%,可接受 |
層隱藏時: body=184, docEl=184
層展開時: IE/FF: body=184, docEl=303 → max=303 ✓
Opera: body=300, docEl=300 → max=300 ✓
Safari: body=303, docEl=184 → max=303 ✓
postMessage 實現跨域高度通知ResizeObserver 監聽子頁面尺寸變化(無輪詢)reinitIframe()此方案在傳統專案中經過大規模驗證,穩定可靠。