`
<iframe src="child.html" id="main" width="100%" frameborder="0" scrolling="no"></iframe>
<script>
$('#main').on('load', function() {
var $body = $(this).contents().find('body');
var h = $body.outerHeight(true); // 含 margin
$(this).height(h + 20); // 留白緩衝
});
<!-- child.html -->
<script>
$(function() {
function resize() {
var h = $(document).outerHeight(true);
parent.$('#main').height(h + 20);
}
$(window).on('load resize', resize);
// 動態內容變更時手動觸發
// $(document).ajaxComplete(resize);
});
受**同源策略**限制,父頁無法直接讀取子頁 DOM。需**代理頁面** 中繞。
parent.a.com/page.html (父頁)
└─ iframe → child.b.com/content.html (子頁)
└─ 隱藏 iframe → parent.a.com/proxy.html (代理)
<!-- child.b.com/content.html -->
<iframe id="proxy" src="https://parent.a.com/proxy.html" style="display:none;"></iframe>
<script>
(function autoHeight() {
var w = Math.max(document.body.scrollWidth, document.body.clientWidth);
var h = Math.max(document.body.scrollHeight, document.body.clientHeight);
var f = document.getElementById('proxy');
f.src = f.src + '#' + w + '|' + h; // 透過 hash 傳遞尺寸
})();
// 內容變動時重新呼叫 autoHeight()
</script>
<!-- parent.a.com/proxy.html -->
<script>
(function() {
var hash = location.hash; // #1200|800
if (hash.indexOf('#') === 0) {
var parts = hash.substring(1).split('|');
var w = parts[0] + 'px';
var h = parts[1] + 'px';
// 同域下可直接操作父頁 DOM
var target = parent.parent.document.getElementById('mainIframe');
if (target) {
target.style.width = w;
target.style.height = h;
}
}
})();
</script>
<iframe src="https://child.b.com/content.html" id="mainIframe" frameborder="0" scrolling="no"></iframe>
**推薦**:不需代理頁,雙向通訊、安全驗證來源。
var iframe = document.getElementById('mainIframe');
iframe.onload = function() {
iframe.contentWindow.postMessage('getHeight', 'https://child.b.com');
};
window.addEventListener('message', function(e) {
if (e.origin !== 'https://child.b.com') return; // 安全驗證
if (e.data && e.data.type === 'iframeHeight') {
iframe.style.height = e.data.height + 'px';
}
});
window.addEventListener('message', function(e) {
if (e.origin !== 'https://parent.a.com') return;
if (e.data === 'getHeight') {
var h = Math.max(document.body.scrollHeight, document.body.offsetHeight);
e.source.postMessage({ type: 'iframeHeight', height: h }, e.origin);
}
});
// 內容動態變化時主動通知
function notifyResize() {
var h = Math.max(document.body.scrollHeight, document.body.offsetHeight);
parent.postMessage({ type: 'iframeHeight', height: h }, 'https://parent.a.com');
}
| 現象 | 原因 | 解決 |
|---|---|---|
| 高度為 0 / 150px | iframe load 時子頁 CSS/圖片/字體未載入完成 | 子頁 `window.onload` 或 `$(window).on('load')` 後再通知;圖片 `onload` 觸發 resize |
| 高度忽大忽小 | 子頁有動畫/折疊面板/懶載入圖片 | 子頁關鍵動作後呼叫 `notifyResize()`;或父頁 `setInterval` 輪詢 (不推薦) |
| 跨域報錯 "Blocked a frame" | 嘗試直接訪問跨域 iframe.contentDocument | 改用 postMessage 或代理頁方案 |
| 白邊/截斷 | 子頁 `body` 有 margin、浮動未清除、absolute 定位 | 子頁 CSS `body{margin:0}`、清除浮動、避免 absolute 脫離流 |