iframe 預設高度固定,內容超出會出現捲軸,內容不足又留白。要讓它自動撐開到剛好包住內容,需要讀取子頁面的實際高度,而這件事在舊時代的寫法相當繁瑣。
腳本開頭有兩個設定項:要自适应的 iframe id 清單,以及不支援 iframe 的瀏覽器是否隱藏該元素。
<script type="text/javascript">
// 需要自動調整高度的 iframe id 清單
// 多個用逗號分隔,例如:["myframe1", "myframe2"];只有一個時不需逗號
var iframeids = ["top1"];
// 不支援 iframe 的瀏覽器是否隱藏該元素:yes 隱藏,no 不隱藏
var iframehide = "yes";
function dyniframesize() {
var dyniframe = new Array();
for (var i = 0; i < iframeids.length; i++) {
if (document.getElementById) {
dyniframe[dyniframe.length] = document.getElementById(iframeids[i]);
if (dyniframe[i] && !window.opera) {
// Netscape 系列用 contentDocument
if (dyniframe[i].contentDocument
&& dyniframe[i].contentDocument.body.offsetHeight) {
dyniframe[i].height = dyniframe[i].contentDocument.body.offsetHeight;
}
// IE 用 Document 大寫,並讀 scrollHeight
else if (dyniframe[i].Document
&& dyniframe[i].Document.body.scrollHeight) {
dyniframe[i].height = dyniframe[i].Document.body.scrollHeight;
}
}
}
// 依設定處理不支援 iframe 的瀏覽器
if ((document.all || document.getElementById) && iframehide == "no") {
var tempobj = document.all ? document.all[iframeids[i]]
: document.getElementById(iframeids[i]);
tempobj.style.display = "block";
}
}
}
if (window.addEventListener)
window.addEventListener("load", dyniframesize, false);
else if (window.attachEvent)
window.attachEvent("onload", dyniframesize);
else
window.onload = dyniframesize;
</script>
三個部分是重點。第一,用 addEventListener 掛 load 事件,確保 iframe 內容已載入才量測;attachEvent 是 IE8 以下的等效寫法。第二,跨瀏覽器取高度:標準瀏覽器用 contentDocument.body.offsetHeight,舊 IE 則是 contentWindow.document.body.scrollHeight(屬性名大寫的 Document)。第三,排除 Opera,因為它當時對 iframe 自适应的處理有自己的一套行為。
今天的瀏覽器已統一,那段判斷可以簡化成:
function resizeIframe(iframe) {
var doc = iframe.contentDocument || iframe.contentWindow.document;
iframe.style.height = doc.documentElement.scrollHeight + 'px';
}
window.addEventListener('load', function () {
document.querySelectorAll('iframe').forEach(resizeIframe);
});
兩個重要前提:父子頁面必須同源,否則讀不到 contentDocument;另外 iframe 內容改變(例如非同步載入資料、圖片延遲載入)時高度也會變,因此需要搭配 iframe.onload 重複量測,或直接用 ResizeObserver 監聽尺寸變化。跨網域情境則只能靠 postMessage 由子頁面主動回報高度。