如果 iframe 的出現是個錯誤,那 iframe 裡再塞一個 iframe 就是錯上加錯——但這種結構在舊系統裡確實天天上演。要在這種巢狀環境中把高度撐開,就得靠 contentWindow 和 contentDocument 這兩個屬性。
window 物件。document 物件。兩者的關係可以這樣理解:iframe.contentWindow.document 就等於 iframe.contentDocument。寫 code 時若必須兼顧舊 IE,走 contentWindow.document 這條路最穩。
巢狀 iframe 的經典痛點是:內層內容變動後,外層仍停在固定的預設高度,出現雙重捲軸或大片空白。解法是從最底層量出高度,一層一層回寫。
function showIframeH() {
var parentWin = parent.document.getElementById("test");
if (!parentWin) return false;
var sub = parentWin.contentWindow.document.getElementById("test2");
if (!sub) return false;
// 量第三層的 body 高度
var thirdHeight = sub.contentWindow.document.body.offsetHeight;
sub.height = thirdHeight; // 回寫第二層 iframe 的高度
// 再量第二層,回寫第一層
var secondHeight = x.contentWindow.document.body.offsetHeight;
x.height = secondHeight;
}
流程拆開來看只有三步:取上層 iframe 節點 → 取它內部的下層 iframe 節點 → 量 body 高度並回寫 height。層數再多,就照同樣模式往上疊。
同源是前提。跨網域時,contentWindow.document 會直接拋錯,這時候只能回頭改用本文前述的 hash 或 postMessage 溝通。
時機比語法更容易出錯。iframe 內的資源(尤其圖片)還在下載時,量到的 body 高度會偏小。實務上會在 iframe 的 onload 裡呼叫高度回報函式,而不是在父頁面一載入就量。
用 offsetHeight 而非 height。前者含 padding 與 border,撐開後才不會出現被切掉的情況。
如果今天可以選擇技術方案,iframe 高度自適應已是個被 postMessage + ResizeObserver 取代的老問題;但在維護既有系統時,上面這段逻辑仍然是最省事的做法。