iframe显示高度自适应 兼容多浏览器

在页面上用了iframe带来方便的同时也带来了麻烦,在IE6里能正常显示的iframe在其他的浏览器里确十分丑陋而不方便。为了解决 IE,Firefox,chrome,safari中iframe显示高度自适应问题上网海找了一遍,试了好几个方案都不妥,最后发现了一个可以正常解决的方案。
首先加入以下的JS代码:

  1. function stateChangeIE(_frame)  
  2. {  
  3.     if (_frame.readyState=="complete")//state: loading ,interactive,   complete  
  4.     {  
  5.         AutoHeight();  
  6.     }    
  7. }  
  8. function stateChangeFirefox(_frame)  
  9. {    
  10.     AutoHeight();  
  11. }  
  12.       
  13. function AutoHeight()  
  14. {  
  15.     if(document.readyState!='complete')  
  16.     {  
  17.         setTimeout( function(){AutoHeight();},50 );  
  18.         return;  
  19.     }  
  20.     else  
  21.     {  
  22.         try  
  23.         {   //IE、fireFox下测试通过  
  24.             var ifobj=document.getElementById("mainFrame");  
  25.             ifobj.style.height = ifobj.contentWindow.document.body.scrollHeight + 0 + "px";  
  26.         }   //注意,别忘了加最后那个"px",不然fireFox下就不起作用了  
  27.         //加的那0是为了让非IE浏览器高度不会一直增加  
  28.         catch(e)  
  29.         {}  
  30.     }  
  31. }  
  32. 其次使用iframe如下:
    1. < iframe src="./welcome.html" name="mainFrame" id="mainFrame"  
    2.                 onreadystatechange="stateChangeIE(this)"  
    3.                 onload="stateChangeFirefox(this)" style="width: 100%; height: 9px"  
    4.                 frameborder="0"></iframe >  

    更改完成了,关闭浏览器重新打开或刷新页面,即可看到正常显示效果。以上代码在IE6,Firfox 3.6.11,Chrome(谷歌浏览器)

    7.0.544.0,Safari 5.0.2版本上显示正常。



posted @ 2012-03-09 08:04  Chaoa  阅读(1739)  评论(0编辑  收藏  举报