DIV CSS 佈局教程網

讓 iframe 高度自動貼合內容:兩種跨瀏覽器寫法
編輯:關於JavaScript     

iframe 最惱人的地方,就是高度得寫死。內容多一點就出現內部捲軸,少一點就留一大塊空白。其實只要讀取內部頁面的實際高度,再回過頭設定 iframe 的高度,問題就解決了。

寫法一:等待 readyState 完成

先把 iframe 的 scrolling 關掉,並掛上 onload:

<iframe src="XXX.htm" width="700px" frameborder="0" id="frmsrc"
  scrolling="no" marginheight="0" onload="AutoIframe()"></iframe>

<script type="text/javascript">
function AutoIframe()
{
  if (document.readyState != 'complete')
  {
    setTimeout(function(){ AutoIframe(); }, 25);
    return;
  }
  else
  {
    var ifobj = document.getElementById("frmsrc");
    ifobj.height = ifobj.contentWindow.document.body.scrollHeight;
  }
}
</script>

這裡的關鍵是那个 25 毫秒的輪詢。iframe 的 onload 觸發時,內部文件不一定真的配置完成,因此先確認 readyState 是 complete 再讀高度,才不會抓到錯誤值。

請注意:XXX.htm 必須與主頁面同源,不可跨網域,否則瀏覽器會基於安全性而禁止讀取。

寫法二:用 SetWinHeight 判斷不同屬性

另一種作法是直接在 onload 中呼叫一個函式,並在裡面分辨瀏覽器使用哪個屬性來回報高度:

<iframe src="dd.html" id="frmMain" name="frmMain" width="99%" height="100%"
  frameborder="0" scrolling="no" marginHeight="0" marginWidth="0"
  onload="Javascript:SetWinHeight(this)"></iframe>

<script>
function SetWinHeight(obj)
{
  var win = obj;
  if (document.getElementById)
  {
    if (win && !window.opera)
    {
      if (win.contentDocument && win.contentDocument.body.offsetHeight)
        win.height = win.contentDocument.body.offsetHeight;
      else if (win.Document && win.Document.body.scrollHeight)
        win.height = win.Document.body.scrollHeight;
    }
  }
}
</script>

這段的精神是:Firefox 用 contentDocument,IE 用 Document,兩邊都試一次即可。

三個實務上的坑

  • 跨網域:同源限制是硬規定。若 iframe 內容來自其他網域,只能改用 postMessage 由內部頁面主動把高度告訴父頁。
  • 內容動態變高:上述兩種寫法都只在載入時計算一次。若 iframe 內有展開收合、動態載入留言等互動,就必須改用 ResizeObserver 或定時重新計算。
  • 不要用 offsetHeight 直接量 body:某些情境下 body 的高度會與實際內容不符,改用 document.documentElement.scrollHeight 通常更準。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved