iframe.contentDocument.body.scrollHeight。postMessage 通訊。function iframeAutoFit(iframe) {
// 延遲執行確保內容渲染完成
setTimeout(function() {
if (!iframe) return;
try {
var doc = iframe.contentDocument || iframe.contentWindow.document;
var height = doc.body.scrollHeight; // 或 doc.documentElement.scrollHeight
iframe.style.height = height + 'px';
} catch (e) {
console.warn('iframe 高度獲取失敗 (跨域?):', e);
}
}, 100);
}
// 使用
<iframe id="myIframe" src="same-origin-page.html" onload="iframeAutoFit(this)"
frameborder="0" scrolling="no" style="width:100%; border:none;"></iframe>
function setupIframeAutoResize(iframe) {
if (!iframe) return;
var resizeTimer;
function resize() {
try {
var doc = iframe.contentDocument || iframe.contentWindow.document;
var height = Math.max(
doc.body.scrollHeight,
doc.documentElement.scrollHeight,
doc.body.offsetHeight,
doc.documentElement.offsetHeight
);
iframe.style.height = height + 'px';
} catch (e) { /* 跨域靜默失敗 */ }
}
// 初始載入
iframe.onload = function() {
resize();
// 監聽 iframe 內圖片載入完成觸發 resize
var doc = iframe.contentDocument || iframe.contentWindow.document;
var images = doc.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
if (!images[i].complete) {
images[i].onload = resize;
}
}
// 監聽 DOM 變動 (AJAX 新增內容等)
if (window.MutationObserver) {
var observer = new MutationObserver(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resize, 50); // 防抖
});
observer.observe(doc.body, { childList: true, subtree: true, attributes: true });
// 儲存 observer 以便清理
iframe._resizeObserver = observer;
}
};
// 父視窗 resize 也觸發 (應對視窗寬度變化導致內容重排)
window.addEventListener('resize', function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resize, 100);
});
}
// 清理
function destroyIframeAutoResize(iframe) {
if (iframe._resizeObserver) iframe._resizeObserver.disconnect();
iframe.onload = null;
}
<iframe id="crossIframe" src="https://other-domain.com/child.html"
frameborder="0" scrolling="no" style="width:100%; border:none; min-height:200px;"></iframe>
<script>
var iframe = document.getElementById('crossIframe');
// 監聽子頁面訊息
window.addEventListener('message', function(e) {
// 安全性:驗證來源
if (e.origin !== 'https://other-domain.com') return;
// 期待格式: { type: 'iframeResize', height: 1234 }
if (e.data && e.data.type === 'iframeResize' && typeof e.data.height === 'number') {
iframe.style.height = e.data.height + 'px';
}
});
// 可選:父頁面主動請求高度 (子頁面需監聽此訊息)
function requestIframeHeight() {
iframe.contentWindow.postMessage({ type: 'requestHeight' }, 'https://other-domain.com');
}
// 定期請求 (備用)
setInterval(requestIframeHeight, 5000);
</script>
<script>
function sendHeight() {
var height = Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight
);
// 發送給父頁面
window.parent.postMessage({ type: 'iframeResize', height: height }, '*'); // * 為示範,生產環境請指定具體父域名
}
// 頁面載入完成
window.addEventListener('load', sendHeight);
// 監聽 DOM 變動
if (window.MutationObserver) {
new MutationObserver(function() { sendHeight(); })
.observe(document.body, { childList: true, subtree: true, attributes: true });
}
// 監聽圖片載入
document.querySelectorAll('img').forEach(function(img) {
if (!img.complete) img.onload = sendHeight;
});
// 回應父頁面主動請求
window.addEventListener('message', function(e) {
if (e.data && e.data.type === 'requestHeight') sendHeight();
});
</script>
GitHub: davidjbradshaw/iframe-resizer
<!-- 父頁面 -->
<script src="iframeResizer.min.js"></script>
<iframe src="child.html" width="100%" scrolling="no"></iframe>
<script>
iFrameResize({ log: false, checkOrigin: false }, '#myIframe');
</script>
<!-- 子頁面 -->
<script src="iframeResizer.contentWindow.min.js"></script>
<!-- 無需其他代碼,自動發送高度 -->
特色:支援跨域、多 iframe、巢狀 iframe、滾動同步、關閉回調、ID 衝突處理、極小體積 (4KB gzip)。
iframe {
display: block; /* 消除底部間隙 */
width: 100%; /* 自適應寬度 */
min-height: 200px; *//* 載入前佔位,防止版面跳動 */
border: none;
background: #fafafa; /* 載入中背景 */
}
/* 父頁面容器 */
.iframe-wrapper {
position: relative;
overflow: hidden; /* 防止內容溢出 */
}
| 場景 | 推薦方案 | 關鍵點 |
|---|---|---|
| 同源、靜態內容 | 方案一 onload | 簡單、零依賴 |
| 同源、動態內容 (AJAX/圖片/互動) | 方案二 MutationObserver | 即時響應、無輪詢 |
| 跨源 (不同域名/協定/埠) | 方案三 postMessage | 標準、安全、雙向 |
| 生產環境、複雜需求、求穩 | 方案四 iframe-resizer | 成熟、功能全、維護性佳 |
scrolling="no" 避免雙滾動條,但需確保高度精確。body { margin: 0; } 避免邊距干擾高度計算。postMessage **務必驗證 e.origin**,防止 XSS。document.domain 降級 (已棄用、不安全、Chrome 移除中)。