網路上關於 iframe 高度自適應的程式碼不少,但品質參差不齊:有的過度複雜,有的存在明顯錯誤。以下這份精簡版本在原稿基礎上修正了一處 Opera 下的問題,實測可用。
<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>
<iframe name="frameContent" src="*" frameborder="0" width="100%"
onload="SetCwinHeight(this)"></iframe>
標示星號處填入 iframe 頁面的位址。要注意的是,src 必須與主頁位於同一網站下,否則會出現「權限被禁止」的錯誤。
另外提醒:如果 iframe 內容的內部頁面沒有明確的檔名或存在跨域情況,取高度時可能得到 0,實作時建議加上重試或延遲呼叫作為保險。