父頁面嵌入 <iframe>,iframe 內文檔的 <html> 元素高度大於 <body>,導致雙重滾動條或異常留白。
html, body { height: 100%; } 但內容超出時表現不一<html> 是文檔根元素,<body> 是其子元素,邊距合併、內邊距、浮動等導致高度不一致html 為準,內容實際在 body 中<style>
html, body {
display: block; /* 重置為標準塊級盒模型 */
height: 100%; /* 可選:鎖定高度 */
margin: 0; /* 消除默認邊距 */
padding: 0; /* 消除默認內邊距 */
overflow: hidden; /* 防止雙滾動條,由父頁面控制 */
}
</style>
<iframe id="myIframe" src="child.html" frameborder="0" style="width: 100%; border: none;"></iframe>
<script>
const iframe = document.getElementById('myIframe');
iframe.onload = function() {
try {
// 獲取子文檔 body 高度
const doc = iframe.contentDocument || iframe.contentWindow.document;
const height = doc.body.scrollHeight;
iframe.style.height = height + 'px';
} catch (e) {
console.warn('跨域無法訪問 iframe 內容', e);
}
};
</script>
/* 針對 iframe 內部頁面 */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html, body {
height: 100%;
overflow: hidden; /* 關鍵:禁止內部滾動 */
}
body {
/* 業務佈局 */
}
若 iframe **跨域**(不同域名/端口/協議),父頁面**無法訪問** iframe.contentDocument。解決方案:
postMessage 通信傳遞高度html, body { display: block; margin: 0; padding: 0; overflow: hidden; }onload 讀取 body.scrollHeight 設置 iframe 高度 display: block; }