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 排除邏輯過時、無跨域支持。
<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 文檔、廣泛兼容。缺陷:同域限制、無動態監聽。
<!-- 父頁面 -->
<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>
scrolling="auto"scrollHeight vs offsetHeight:前者包含滾動隱藏部分,後者僅可視區box-sizing: border-box 影響高度計算float/absolute 元素導致 body.scrollHeight 為 0,需 overflow:hidden 或檢測 documentElement.scrollHeightinitial-scale=1iframe.style.display='none'; iframe.offsetHeight; iframe.style.display='block';