萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

iframe 自適應高度完整解決方案:三種方案兼容性對比與最佳實踐

iframe 高度自適應:跨域/同域、現代/舊瀏覽器全場景覆蓋

iframe 無法像普通元素隨內容撐開高度,導致內部滾動條或內容截斷。本文提供三種方案:簡易版、經典兼容版、現代跨域通信版,覆蓋 IE6+ 到現代瀏覽器。

方案一:簡易版 (同域、現代瀏覽器)

function SetWinHeight(obj) {
  var win = obj;
  if (document.getElementById && win && !window.opera) {
    if (win.contentDocument && win.contentDocument.body.offsetHeight) {
      win.height = win.contentDocument.body.offsetHeight;
    } else if (win.Document && win.Document.body.scrollHeight) {
      win.height = win.Document.body.scrollHeight;
    }
  }
}

// HTML
<iframe id="win" name="win" src="1.htm" 
  onload="Javascript:SetWinHeight(this)" 
  frameborder="0" scrolling="no" width="778" height="200"></iframe>

缺陷:依賴 onload、不處理動態內容變化、Opera 排除邏輯過時、無跨域支持。

方案二:經典兼容版 (IE6-IE11、Firefox、Chrome、Safari、Opera)

<iframe src="https://example.com/" id="iframepage" name="iframepage" 
  frameBorder="0" scrolling="no" width="100%" onLoad="iFrameHeight()"></iframe>

<script>
function iFrameHeight() {
  var ifm = document.getElementById("iframepage");
  // 兼容 IE (document.frames) 和標準 (contentDocument)
  var subWeb = document.frames ? document.frames["iframepage"].document : ifm.contentDocument;
  if (ifm != null && subWeb != null) {
    ifm.height = subWeb.body.scrollHeight;
  }
}
</script>

優勢:雙模式訪問 iframe 文檔、廣泛兼容。缺陷:同域限制、無動態監聽。

方案三:現代跨域通用方案 (postMessage + ResizeObserver)

<!-- 父頁面 -->
<iframe id="child-frame" src="https://child-domain.com/page.html" 
  style="width:100%; border:none; min-height:300px;"></iframe>

<script>
const iframe = document.getElementById('child-frame');

// 監聽子頁面發送的高度消息
window.addEventListener('message', (e) => {
  // 安全:驗證來源
  if (e.origin !== 'https://child-domain.com') return;
  if (e.data.type === 'iframe:resize') {
    iframe.style.height = e.data.height + 'px';
  }
});

// 兜底:ResizeObserver 監聽同域 iframe 內容變化
if (iframe.contentDocument) {
  new ResizeObserver(() => {
    iframe.style.height = iframe.contentDocument.body.scrollHeight + 'px';
  }).observe(iframe.contentDocument.body);
}
</script>

<!-- 子頁面 (需控制權) -->
<script>
function reportHeight() {
  const height = document.body.scrollHeight;
  parent.postMessage({ type: 'iframe:resize', height }, 'https://parent-domain.com');
}

// 初始報告
reportHeight();

// 監聽 DOM 變化 (動態內容)
new MutationObserver(reportHeight).observe(document.body, { 
  childList: true, subtree: true, characterData: true 
});

// 圖片載入觸發重新計算
document.querySelectorAll('img').forEach(img => {
  img.onload = reportHeight;
});
</script>

方案選型決策樹

  1. 同域 + 靜態內容:方案二 (最簡單、兼容性好)
  2. 同域 + 動態內容 (AJAX/Vue/React):方案三 ResizeObserver 兜底
  3. 跨域 + 可控制子頁面:方案三 postMessage (唯一標準跨域方案)
  4. 跨域 + 不可控制子頁面:無完美方案,只能固定高度或 scrolling="auto"

常見坑點避雷

  • scrollHeight vs offsetHeight:前者包含滾動隱藏部分,後者僅可視區
  • CSS box-sizing: border-box 影響高度計算
  • 內部 float/absolute 元素導致 body.scrollHeight 為 0,需 overflow:hidden 或檢測 documentElement.scrollHeight
  • 移動端 viewport 縮放導致高度計算偏差,需 initial-scale=1
  • Safari iframe 高度渲染 Bug,需觸發重排:iframe.style.display='none'; iframe.offsetHeight; iframe.style.display='block';
copyright © 萬盛學電腦網 all rights reserved