由於最近想實現網頁局部重新整理,使用的IFrame,只要給IFrame賦給新的src值,便可以載入不同的頁面了。但讓人煩惱的問題也隨之而來了,那便是如何讓IFrame自身的高度隨子頁面而變化。上網搜了好多方法,發現都不適用。
很多人的方法都是這樣的。在IFrame中設定 onload="autoHeight();“
function autoHeight(){
var iframe =document.getElementById("container");
if(iframe.Document){//ie自有屬性
iframe.style.height =iframe.Document.documentElement.scrollHeight;
}elseif(iframe.contentDocument){//ie,firefox,chrome,opera,safari
iframe.height =iframe.contentDocument.body.offsetHeight ;
}
}
這種方法在FireFox和Chrome中顯示很好,但是在IE中完全不好使,後來才發現,在IE中不能用iframe.Document,得用iframe.contentWindow。
修改之後的代碼為:
function autoHeight(){
var iframe = document.getElementById("container");
if(iframe.Document){//ie自有屬性
iframe.style.height = iframe.contentWindow.document.body.scrollHeight+20;
}else if(iframe.contentDocument){//ie,firefox,chrome,opera,safari
iframe.height=10;
iframe.height = iframe.contentDocument.body.offsetHeight;
}
}
這樣在IE、FireFox和Chrome中就都好使了。