受同源策略限制,父頁面無法直接讀取跨域 iframe 內部文檔高度。同域情況下,可通過 iframe.contentDocument.body.offsetHeight 或 iframe.contentWindow.document.body.scrollHeight 獲取內容高度,再動態設置 iframe 的 height 屬性。
function SetCwinHeight(obj) {
var cwin = obj;
if (document.getElementById) {
if (cwin && !window.opera) {
// 標準瀏覽器
if (cwin.contentDocument && cwin.contentDocument.body.offsetHeight) {
cwin.height = cwin.contentDocument.body.offsetHeight + 30; // 留白
}
// IE 兼容
else if (cwin.Document && cwin.Document.body.scrollHeight) {
cwin.height = cwin.Document.body.scrollHeight + 30;
}
}
}
}
<iframe
id="IframeId_help"
scrolling="no"
onload="Javascript:SetCwinHeight(this)"
width="670px"
style="border: 0px"
frameborder="0">
</iframe>
若 iframe 頁面與父頁面不同源,必須使用 postMessage 通訊:
<script>
function sendHeight() {
var height = document.body.scrollHeight; // 或 document.documentElement.scrollHeight
parent.postMessage({type: 'iframeHeight', height: height}, '*'); // 生產環境請指定具體域名
}
// 頁面加載完成、內容變化時調用
window.onload = sendHeight;
window.onresize = sendHeight;
// 若有動態內容(AJAX、圖片加載),在內容渲染後手動調用 sendHeight()
</script>
<script>
window.addEventListener('message', function(event) {
// 安全驗證:檢查來源域名
if (event.origin !== 'https://trusted-child-domain.com') return;
var data = event.data;
if (data && data.type === 'iframeHeight') {
var iframe = document.getElementById('IframeId_help');
if (iframe) {
iframe.style.height = data.height + 'px';
}
}
}, false);
</script>
onload 或使用 ResizeObserver 監聽內容變化。margin、padding、box-sizing 會影響高度計算,建議重置樣式。scrolling="no" 並由父頁面控制滾動,體驗更佳。同域用 contentDocument.body.offsetHeight 直觀簡單;跨域必須用 postMessage 協作。現代項目推薦封裝成可復用組件(Vue/React 中用 ref + useEffect 監聽),統一處理加載、錯誤、銷毀邏輯。