contentWindow 與 contentDocument 是訪問 iframe 內部窗口/文檔對象的兩大核心屬性。本文詳細對比其瀏覽器兼容性,並實戰演示**三層 iframe 嵌套**場景下,從頂層依次設置中層、底層 iframe 高度實現完美自適應。
| 屬性 | 返回值 | IE 支援 | Firefox/Chrome/Safari/Edge | 備註 |
|---|---|---|---|---|
iframe.contentWindow | iframe 內部 window 對象 | IE5.5+ ✅ | 全支援 ✅ | **最通用**,可訪問 window 所有屬性方法 |
iframe.contentDocument | iframe 內部 document 對象 | IE8+ ✅ (IE6/7 ❌) | 全支援 ✅ | 等價於 contentWindow.document,直接操作 DOM 更便捷 |
// 兼容所有瀏覽器的獲取 iframe document 方式
function getIframeDocument(iframeEl) {
return iframeEl.contentWindow.document; // 或 iframeEl.contentDocument (IE8+)
}
// 獲取 iframe window
function getIframeWindow(iframeEl) {
return iframeEl.contentWindow;
}
場景:頂層頁面 → `
function syncIframeHeight() {
// 1. 獲取頂層中第一層 iframe 元素
var parentIframe = parent.document.getElementById("test"); // 假設當前腳本在中層頁面
if (!parentIframe) return false;
// 2. 穿透到第二層 iframe
var childIframe = parentIframe.contentWindow.document.getElementById("test2");
if (!childIframe) return false;
// 3. 獲取第三層 (底層內容頁) body 實際高度
var thirdHeight = childIframe.contentWindow.document.body.offsetHeight;
// 4. 設置第二層 iframe 高度
childIframe.height = thirdHeight; // 或 childIframe.style.height = thirdHeight + 'px';
// 5. 獲取第二層 (中層) body 高度 (此時已被撐開)
var secondHeight = parentIframe.contentWindow.document.body.offsetHeight;
// 6. 設置第一層 (頂層) iframe 高度
// 假設頂層頁面中第一層 iframe 的 id 為 "x" (或在頂層頁面調用時獲取)
var topIframe = window.top.document.getElementById("x"); // 需根據實際 ID 調整
if (topIframe) topIframe.height = secondHeight;
// console.log('三層高度同步完成:', thirdHeight, secondHeight);
}
// 掛載點建議:
// 1. 底層頁面 onload / 內容動態變更後 調用 parent.syncIframeHeight()
// 2. 或頂層頁面 setInterval 輪詢 (不推薦)
// 3. 現代方案:底層 postMessage 通知頂層 {type: 'resize', height: ...}
parent.document.getElementById('test').contentWindow.document.getElementById('test2').contentWindow.document.body — 每層都需同域否則拋錯。offsetHeight,否則高度為 0。建議監聽 window.onload 或使用 imagesLoaded 庫。margin:0; padding:0; border:0; overflow:hidden; 避免額外間隙。parent.postMessage({type:'resize', height: document.body.scrollHeight}, '*'),頂層監聽更新對應 iframe 高度,**解耦層級結構**,支援跨域。iframe.contentDocument.body 尺寸變化自動同步,無需輪詢、無需子頁配合 (同域前提)。掌握 contentWindow/contentDocument 差異與多層穿透技巧,是處理嵌入式頁面、編輯器預覽、報表嵌套等場景的硬核基本功。