萬盛學電腦網

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

iframe 自適應高度:子頁面 onload 通知父頁面動態調整高度實現方案

iframe 高度自適應:子頁面主動通知父頁面調整高度模式

與父頁面輪詢不同,此方案由 **子頁面** 在 `onload` 時主動調用父頁面的 iframe 元素設置高度,邏輯清晰、耦合度低,適合同域嵌入場景。

核心實現 (Groovy/JS 語法)

<!-- 子頁面 (frame1.jsp) -->
<script>
function IFrameResize() {
  // 1. 獲取當前頁面文檔高度
  var pageHeight = this.document.body.scrollHeight;
  
  // 2. 獲取父頁面中的 iframe 元素 (需知父頁面 iframe id)
  var obj = parent.document.getElementById("childFrame");
  
  // 3. 設置父頁面 iframe 高度
  obj.height = pageHeight;
}
</script>

<body onload="IFrameResize()">
  <!-- 子頁面內容 -->
</body>
<!-- 父頁面 -->
<IFRAME 
  border="0" 
  marginWidth="0" 
  frameSpacing="0" 
  marginHeight="0" 
  src="frame1.jsp" 
  frameBorder="0" 
  noResize 
  scrolling="no" 
  width="100%" 
  height="100%" 
  vspale="0" 
  id="childFrame">
</IFRAME>

關鍵點解析

環節說明注意事項
觸發時機子頁面 `body.onload`確保圖片/字體/子 iframe 已載入,否則高度不準
高度獲取`document.body.scrollHeight`含 padding、不含 margin;浮動/絕對定位子元素可能導致 0
跨域訪問`parent.document.getElementById`**同域前提**,跨域會拋錯誤
父頁面 iframe 屬性`scrolling="no"` `noResize`禁用內部滾動條、禁用用戶拖拽,由父頁面統一控制
ID 對應子頁面硬編碼 `"childFrame"`耦合風險,建議約定全局變量或 `postMessage` 傳遞

健壯性增強版

<!-- 子頁面增強版 -->
<script>
function IFrameResize() {
  try {
    // 兼容性高度獲取
    var height = Math.max(
      document.body.scrollHeight,
      document.body.offsetHeight,
      document.documentElement.scrollHeight,
      document.documentElement.offsetHeight
    );
    
    // 安全訪問父頁面
    if (window.parent && window.parent.document) {
      var iframe = window.parent.document.getElementById("childFrame");
      if (iframe) {
        iframe.style.height = height + "px"; // 用 style.height 覆蓋屬性
        // 可選:通知父頁面其他邏輯
        if (window.parent.onIframeResized) window.parent.onIframeResized(height);
      }
    }
  } catch (e) {
    console.warn('iframe resize failed:', e); // 跨域會進入 catch
  }
}

// 圖片載入後重新計算
window.addEventListener('load', IFrameResize); // load 事件包含圖片

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

現代跨域版 (postMessage 雙向通信)

<!-- 父頁面 -->
<iframe id="childFrame" src="https://child.example.com/page.html" 
  style="width:100%; border:none;" scrolling="no"></iframe>

<script>
const iframe = document.getElementById('childFrame');
window.addEventListener('message', (e) => {
  if (e.origin !== 'https://child.example.com') return;
  if (e.data.type === 'resize') {
    iframe.style.height = e.data.height + 'px';
  }
});
</script>

<!-- 子頁面 -->
<script>
function reportHeight() {
  const height = Math.max(
    document.body.scrollHeight, document.documentElement.scrollHeight
  );
  parent.postMessage({ type: 'resize', height }, 'https://parent.example.com');
}

window.addEventListener('load', reportHeight);
new MutationObserver(reportHeight).observe(document.body, { 
  childList: true, subtree: true 
});
</script>

與方案對比 (參考文章 35137)

  • 父頁面輪詢 (35137 方案一/二):父頁面主動讀取,同域簡單,跨域不可行
  • 子頁面主動通知 (本文):邏輯清晰,但需子頁面配合,同域/跨域均可 (postMessage)
  • ResizeObserver (現代同域最佳):無需子頁面代碼,自動監測內容尺寸變化
copyright © 萬盛學電腦網 all rights reserved