萬盛學電腦網

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

JavaScript 控制 iframe 自適應高寬度完整解決方案

核心難點:跨域限制與時機控制

iframe 自適應高度面臨兩大挑戰:

  1. 同源策略:父頁無法直接讀取跨域 iframe 內部 document.body.scrollHeight。
  2. 載入時機:必須在 iframe 內容完全渲染後(圖片、字體、異步數據)再測量高度。

同域方案:父頁直接控制

方案 A:iframe 頁面主動通知父頁(推薦)

// iframe 內頁面 (child.html)
window.onload = function() {
    // 確保圖片等資源載入完成
    var height = document.body.scrollHeight;
    parent.postMessage({type: 'resize', height: height}, '*');
};

// 父頁面 (parent.html)
window.addEventListener('message', function(e) {
    if (e.data.type === 'resize') {
        document.getElementById('myIframe').style.height = e.data.height + 'px';
    }
});

方案 B:父頁輪詢檢測(不推薦,效能差)

// 父頁面
$('#myIframe').on('load', function() {
    var iframe = this;
    function checkHeight() {
        try {
            var h = iframe.contentWindow.document.body.scrollHeight;
            iframe.style.height = h + 'px';
        } catch (e) {
            // 跨域會拋錯
        }
    }
    checkHeight();
    setInterval(checkHeight, 500); // 定期檢測動態內容變化
});

跨域方案:postMessage + 代理頁面

架構圖解

parent.html (domain A) 
    └─ iframe → child.html (domain B)
                    └─ iframe → agent.html (domain A, 隱藏)

實現步驟

  1. child.html (domain B):計算高度 → 嵌入同域 agent.html → 將高度編碼進 agent.html#height。
  2. agent.html (domain A):解析 hash → parent.parent.postMessage 或直接操作頂層 iframe 高度。
  3. parent.html (domain A):接收消息 → 設置 iframe 高度。

現代最佳實踐:postMessage 標準化方案

// 父頁面
<iframe id="childFrame" src="https://domain-b.com/child.html" frameborder="0" scrolling="no"></iframe>

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

// 子頁面 (domain B)
function reportHeight() {
    var height = Math.max(
        document.body.scrollHeight,
        document.documentElement.scrollHeight,
        document.body.offsetHeight,
        document.documentElement.offsetHeight
    );
    parent.postMessage({type: 'iframeResize', height: height}, 'https://domain-a.com');
}

// 頁面載入、窗口變化、異步數據更新後均調用
window.addEventListener('load', reportHeight);
window.addEventListener('resize', reportHeight);
// 業務邏輯:數據渲染完成後
fetchData().then(render).then(reportHeight);

常見坑點避坑指南

  • box-sizing:確保 iframe 無 padding/border 干擾高度計算。
  • 最小高度:設定 min-height 防止內容為空時塌陷。
  • 滾動條:父頁 scrolling="no",子頁內容超出自動滾動。
  • 動態內容:AJAX 載入、圖片懶加載、字體載入後均需重新通知高度變化。
copyright © 萬盛學電腦網 all rights reserved