DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML和Xhtml
iframe 高度自適應的精簡寫法(相容 FF、Opera、Safari)
編輯:HTML和Xhtml     

網路上關於 iframe 高度自適應的程式碼不少,但品質參差不齊:有的過度複雜,有的存在明顯錯誤。以下這份精簡版本在原稿基礎上修正了一處 Opera 下的問題,實測可用。

JavaScript 部分

<script type="text/javascript">
function SetCwinHeight(iframeObj){
  if (document.getElementById){
    if (iframeObj){
      if (iframeObj.contentDocument && iframeObj.contentDocument.body.offsetHeight){
        iframeObj.height = iframeObj.contentDocument.body.offsetHeight;
      } else if (document.frames[iframeObj.name].document && document.frames[iframeObj.name].document.body.scrollHeight){
        iframeObj.height = document.frames[iframeObj.name].document.body.scrollHeight;
      }
    }
  }
}
</script>

HTML 部分

<iframe name="frameContent" src="*" frameborder="0" width="100%"
        onload="SetCwinHeight(this)"></iframe>

標示星號處填入 iframe 頁面的位址。要注意的是,src 必須與主頁位於同一網站下,否則會出現「權限被禁止」的錯誤。

另外提醒:如果 iframe 內容的內部頁面沒有明確的檔名或存在跨域情況,取高度時可能得到 0,實作時建議加上重試或延遲呼叫作為保險。

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