DIV CSS 佈局教程網

讓 iframe 高度自適應內容:相容 IE 與 Firefox 的實作
編輯:關於JavaScript     

問題的由來

iframe 內頁面的高度是動態的,但 iframe 標籤本身需要明確高度,於是內容被裁切或出現雙捲軸。這個問題困擾過很多人,網路上號稱相容 Firefox 的程式碼不少,真正好用的卻不多。

做法一:onload 時量測並設定高度

先在 body 中加入這段函式:

<script language="javascript">
function adjustFrameSize() {
  var frm = document.getElementById("iframe1");   // 第一處要改:換成你的 iframe id
  var subWeb = document.frames ? document.frames["iframe1"].document : frm.contentDocument;

  if (frm != null && subWeb != null) {
    frm.style.height = "0px";   // 先歸零,否則會殘留上一次的高度
    frm.style.height = subWeb.documentElement.scrollHeight + "px";
    frm.style.width  = subWeb.documentElement.scrollWidth + "px";
    subWeb.body.style.overflowX = "auto";
    subWeb.body.style.overflowY = "auto";
  }
}
</script>

然後在 iframe 標籤上掛 id 與 onload(第二處要改的地方):

<iframe id="iframe1" onload="adjustFrameSize()" scrolling="no"
        src="iframe1.html" width="100%" height="300px" frameborder="0"></iframe>

幾個重點:document.frames[...] 是 IE 的取法,contentDocument 是標準取法,用三元運算子一次相容兩邊;把高度先設為 0 是必要的,否則當新頁面比舊頁面矮時,高度不會縮回去;最後記得把 scrolling 設為 no,避免內外兩層捲軸。

做法二:內容動態變化時怎麼辦

上面那招只在 iframe 載入完成的那一刻生效。如果子頁面裡有 AJAX 載入、或透過 JS 動態插入內容導致高度改變,就得讓子頁面主動通知父頁面。常見手法是透過 hash 傳遞高度:

子頁面在 DOM 變動後呼叫:

// 修改父視窗的 hash 來傳遞高度
function changeHeight(){
  window.top.location.hash = "#height=" + $(document).height();
}

父頁面持續輪詢 hash 並套用:

var iframe = document.getElementById("iframe1");

function iframeHeight() {
  var hash = window.location.hash.slice(1), h;
  if (hash && /height=/.test(hash)) {
    h = hash.replace("height=", "");
    iframe.style.height = h + "px";
    window.location.hash = "#temp";   // 清掉,避免下次點連結時高度沒更新
  }
  setTimeout(iframeHeight, 100);
}
iframeHeight();

更現代的替代方案:postMessage

用 hash 傳值算是權宜之計,缺點是要靠 setTimeout 輪詢,且 hash 會污染網址。如今跨視窗溝通的正規做法是 postMessage:

// 子頁面
parent.postMessage({ type: "resize", height: document.documentElement.scrollHeight }, "*");

// 父頁面
window.addEventListener("message", function(e){
  if (e.data && e.data.type === "resize") {
    document.getElementById("iframe1").style.height = e.data.height + "px";
  }
});

事件驅動、不必輪詢,也能明確限制來源(把 "*" 換成特定網域)。若 iframe 與父頁面同源,其實還有更簡單的選擇:直接不用 iframe,或用 ResizeObserver 監聽子頁面 body 尺寸變化後調整。另外要提醒,iframe 高度自適應本質上是繞過 iframe 隔離特性的 hack,若只是為了版面整合,先評估能否改用純 CSS 或前端元件取代,往往更省事。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved