iframe 自適應高度:隱藏 border/scrollbar,讓用戶感知不到 iframe 存在。若內頁固定高度可寫死;若切換頁面或 DOM 動態操作,需程序同步高度。
傳統兩法:
onload 取內頁高同步維護角度法二優於法一(避免每頁重複代碼)。但兩法僅處理靜態載入,DOM 動態變化無法捕捉。
父頁 setInterval 每 200ms 讀取內頁高度同步。測試 5 瀏覽器(IE6/7/FF/Opera/Safari)同時運行,CPU 佔用 0%,甚至 2ms 也無壓力。
<iframe id="frame_content" src="iframe_b.html" scrolling="no" frameborder="0"></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){}
}
window.setInterval("reinitIframe()", 200);
</script>
| 瀏覽器 | 層隱藏 bHeight | 層隱藏 dHeight | 層展開 bHeight | 層展開 dHeight |
|---|---|---|---|---|
| IE6 | 184 | 184 | 184 | 303 |
| IE7 | 184 | 184 | 184 | 303 |
| FF | 184 | 184 | 184 | 303 |
| Opera | 181 | 181 | 300 | 300 |
| Safari | 184 | 184 | 303 | 184 |
規律:**取 body.scrollHeight 與 documentElement.scrollHeight 最大值可全兼容**。絕對定位層、float 均會導致兩值差異。
非 IE 瀏覽器:層展開後隱藏,高度仍維持展開值;頁面切換從高到矮同樣。原因:iframe 窗體高度高於文檔時取窗體高,低於時取文檔高。
解決:iframe 加 onload="this.height=100" 載入先縮矮,再同步實際高度。實際項目中因成本考慮未實施(每個 DOM 函數插代碼代價高),縮不回去非致命。
<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){}
}
setInterval(reinitIframe, 200);
</script>