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