Google 搜「iframe 自適應高度」超 5 萬條,但多為靜態加載方案,鮮有解決 JS 操作 DOM 後的動態高度同步 與 全瀏覽器兼容 的深度實踐。本文針對這兩大痛點,給出生產級解決方案。
隱藏 iframe border/scrollbar,使其融合為主頁一體。若內嵌頁固定高度,寫死即可;若涉及頁面切換或 DOM 動態操作,需實時同步 `iframe.height = 內嵌頁實際高度`。
主頁設置 `setInterval` 每 200ms 讀取內嵌頁高度並同步。測試證實:5 瀏覽器並發,CPU 佔用 0%,甚至 2ms 間隔無壓力。
測試矩陣(含絕對定位層展開/收起):
| 瀏覽器 | 層隱藏 bHeight | 層隱藏 dHeight | 層展開 bHeight | 層展開 dHeight |
|---|---|---|---|---|
| IE6/7 | 184 | 184 | 184 | 303 |
| FF | 184 | 184 | 184 | 303 |
| Opera | 181 | 181 | 300 | 300 |
| Safari | 184 | 184 | 303 | 184 |
規律:無絕對定位/float 時兩值相等;有差異時,取 `Math.max(bHeight, dHeight)` 可全兼容。
現象:層收起/切換到矮頁面時,高度卡在最大值無法縮回(iframe 窗體高度 > 文檔高度時,取窗體高度)。
解決思路:同步前先將 iframe 高度重置為極小值(如 100px),再同步實際高度。實現:`
權衡:每個 DOM 操作函數插入重置代碼成本過高,實際專案中常接受「只長不縮」的非致命體驗損失。若有更優方案(如 `ResizeObserver`、postMessage 通知),歡迎交流。
<iframe id="frame_content" src="iframe_b.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;
iframe.height = Math.max(bHeight, dHeight);
}catch(ex){}
}
window.setInterval("reinitIframe()", 200);
</script>
註:嚴格模式 Doctype 為測試基準;無 Doctype 會導致怪異模式,兼容性不可控。