萬盛學電腦網

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

Iframe 自適應高度的 JavaScript 實現方案

核心難點

受同源策略限制,父頁面無法直接讀取跨域 iframe 內部文檔高度。同域情況下,可通過 iframe.contentDocument.body.offsetHeight 或 iframe.contentWindow.document.body.scrollHeight 獲取內容高度,再動態設置 iframe 的 height 屬性。

同域通用代碼

function SetCwinHeight(obj) {
  var cwin = obj;
  if (document.getElementById) {
    if (cwin && !window.opera) {
      // 標準瀏覽器
      if (cwin.contentDocument && cwin.contentDocument.body.offsetHeight) {
        cwin.height = cwin.contentDocument.body.offsetHeight + 30; // 留白
      }
      // IE 兼容
      else if (cwin.Document && cwin.Document.body.scrollHeight) {
        cwin.height = cwin.Document.body.scrollHeight + 30;
      }
    }
  }
}

HTML 調用示例

<iframe 
  id="IframeId_help" 
  scrolling="no" 
  onload="Javascript:SetCwinHeight(this)" 
  width="670px" 
  style="border: 0px" 
  frameborder="0">
</iframe>

跨域解決方案(現代標準)

若 iframe 頁面與父頁面不同源,必須使用 postMessage 通訊:

子頁面(被嵌入頁)發送高度

<script>
function sendHeight() {
  var height = document.body.scrollHeight; // 或 document.documentElement.scrollHeight
  parent.postMessage({type: 'iframeHeight', height: height}, '*'); // 生產環境請指定具體域名
}
// 頁面加載完成、內容變化時調用
window.onload = sendHeight;
window.onresize = sendHeight;
// 若有動態內容(AJAX、圖片加載),在內容渲染後手動調用 sendHeight()
</script>

父頁面接收並設置高度

<script>
window.addEventListener('message', function(event) {
  // 安全驗證:檢查來源域名
  if (event.origin !== 'https://trusted-child-domain.com') return;
  
  var data = event.data;
  if (data && data.type === 'iframeHeight') {
    var iframe = document.getElementById('IframeId_help');
    if (iframe) {
      iframe.style.height = data.height + 'px';
    }
  }
}, false);
</script>

常見問題與優化

  • 內容延遲加載:圖片、Web 字體加載完成前高度會變,建議在圖片 onload 或使用 ResizeObserver 監聽內容變化。
  • CSS 影響:iframe 內頁面的 margin、padding、box-sizing 會影響高度計算,建議重置樣式。
  • 滾動條:設置 scrolling="no" 並由父頁面控制滾動,體驗更佳。
  • 動態移除:iframe 移除時記得清理事件監聽,防止內存洩漏。

總結

同域用 contentDocument.body.offsetHeight 直觀簡單;跨域必須用 postMessage 協作。現代項目推薦封裝成可復用組件(Vue/React 中用 ref + useEffect 監聽),統一處理加載、錯誤、銷毀邏輯。

copyright © 萬盛學電腦網 all rights reserved