萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

iframe 自適應高度完整解決方案:同域、跨域、動態內容全覆蓋

核心難點回顧

  • 同源策略:跨域 iframe 無法直接訪問 contentDocument.body.scrollHeight。
  • 動態內容:AJAX 載入、圖片懶加載、字體渲染、用戶交互展開均導致高度變化。
  • 時機控制:必須在內容「穩定」後測量,避免高度抖動。

方案一:同域 - 父頁監聽 load 事件 (最簡單)

<!-- 父頁面 -->
<iframe id="myFrame" src="child.html" frameborder="0" scrolling="no" style="width:100%;"></iframe>

<script>
$('#myFrame').on('load', function() {
    var $iframe = $(this);
    // 延遲確保內部圖片/字體渲染完成
    setTimeout(function() {
        try {
            var height = $iframe[0].contentWindow.document.body.scrollHeight;
            $iframe.height(height + 20); // 留白緩衝
        } catch (e) {
            console.error('同域高度獲取失敗:', e);
        }
    }, 100);
});
</script>

方案二:同域 - 子頁主動通知父頁 (推薦,響應動態變化)

<!-- 子頁面 child.html -->
<script>
function reportHeight() {
    var height = Math.max(
        document.body.scrollHeight,
        document.documentElement.scrollHeight,
        document.body.offsetHeight,
        document.documentElement.offsetHeight
    );
    // 發送給父頁
    parent.postMessage({type: 'iframeResize', height: height}, '*'); // 生產環境指定具體域
}

// 頁面載入
window.addEventListener('load', reportHeight);
// 窗口變化
window.addEventListener('resize', reportHeight);
// 業務動態更新後 (AJAX 完成、圖片 onload、元素展開/折疊)
function afterContentChange() {
    // nextTick 確保佈局更新
    requestAnimationFrame(reportHeight);
}
</script>

<!-- 父頁面 -->
<script>
window.addEventListener('message', function(e) {
    // 安全驗證來源
    if (e.origin !== 'https://trusted-child-domain.com') return;
    if (e.data.type === 'iframeResize') {
        document.getElementById('myFrame').style.height = e.data.height + 'px';
    }
});
</script>

方案三:跨域 - postMessage 標準方案 (現代標準)

同方案二,但父子頁面域不同。關鍵點:

  • 子頁 parent.postMessage(data, parentOrigin) 指定目標源。
  • 父頁 e.origin 驗證來源合法性。
  • 無需代理頁面,現代瀏覽器全支援 (IE8+ 支援 postMessage)。

方案四:跨域 - 代理頁面技術 (舊 IE 兼容)

架構:
parent.html (domain A)
  └─ iframe → child.html (domain B)
                └─ iframe → agent.html (domain A, 隱藏, src="agent.html#width|height")

流程:
1. child.html 計算高寬 → 設置 agent.html src = "agent.html#w|h" (觸發重載)
2. agent.html 解析 hash → parent.parent.document.getElementById('iframeId').style.height = h
3. 利用同源策略:agent.html 與 parent.html 同域,可操作父頁 DOM

代碼實現

<!-- child.html (domain B) -->
<iframe id="proxy" src="https://domain-a.com/agent.html" style="display:none"></iframe>
<script>
function syncSize() {
    var w = Math.max(document.body.scrollWidth, document.documentElement.scrollWidth);
    var h = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    document.getElementById('proxy').src = 'https://domain-a.com/agent.html#' + w + '|' + h;
}
window.onload = syncSize;
window.onresize = syncSize;
// 動態內容更新後調用 syncSize()
</script>

<!-- agent.html (domain A) -->
<script>
window.onload = function() {
    var hash = location.hash; // #1200|800
    if (hash.indexOf('#') === 0) {
        var parts = hash.substring(1).split('|');
        var w = parts[0] + 'px', h = parts[1] + 'px';
        // 操作頂層父頁的 iframe
        var topFrame = window.parent.parent.document.getElementById('myFrame');
        if (topFrame) {
            topFrame.style.width = w;
            topFrame.style.height = h;
        }
    }
};
</script>

方案五:舊版 jQuery load 事件寫法 (歷史參考)


// 父頁面寫法 (放在 iframe 後面)
$('#mainframe').on('load', function() {
    var h = $(this).contents().find('body').height() + 30;
    $(this).height(h);
});

// 子頁面寫法
$(window.parent.document).find('#mainframe').on('load', function() {
    var h = $(document).height() + 30;
    $(this).height(h);
});

動態內容高度變化監聽進階方案

MutationObserver 監聽 DOM 變化


// 子頁面
var observer = new MutationObserver(function(mutations) {
    // 過濾屬性變化、字符數據變化,僅關注結構變化
    var hasStructuralChange = mutations.some(function(m) {
        return m.type === 'childList' || m.type === 'characterData';
    });
    if (hasStructuralChange) reportHeight();
});

observer.observe(document.body, {
    childList: true,
    subtree: true,
    characterData: true
});

ResizeObserver 監聽元素尺寸變化 (現代最佳)


// 子頁面
var resizeObserver = new ResizeObserver(function(entries) {
    for (var entry of entries) {
        if (entry.target === document.body) {
            reportHeight();
            break;
        }
    }
});
resizeObserver.observe(document.body);

綜合建議選型表

場景推薦方案關鍵點
同域、靜態內容方案一 (load 事件)簡單、無需修改子頁
同域、動態內容方案二 (postMessage)實時、雙向通信、擴展性強
跨域、現代瀏覽器方案三 (postMessage)標準、安全、無代理頁
跨域、需支援 IE8-方案四 (代理頁)繞過同源限制、維護成本高
嵌入第三方無法修改方案一 + 定時輪詢最後手段、效能差

避坑清單

  1. box-sizing: border-box 確保 padding/border 不影響高度計算。
  2. 最小高度:min-height: 200px 防止空頁塌陷。
  3. 滾動條:父頁 scrolling="no" overflow:hidden,子頁自行滾動。
  4. 緩存破壞:代理頁面 src 加時間戳 agent.html?t=xxx#w|h 強制重載。
  5. 多重 iframe 嵌套:用 window.top 定位頂層,window.parent 定位直接父級。
copyright © 萬盛學電腦網 all rights reserved