JavaScript應用:Iframe自適應其加載的內容高度

main.htm:

<html>  
    
<head>  
       
<meta  http-equiv='Content-Type'  content='text/html;  charset=gb2312' />  
       
<meta  name='author'  content='F.R.Huang(meizz梅花雪)//www.meizz.com' />  
       
<title>iframe自適應加載的頁面高度</title>  
    
</head>  
     
    
<body>
        
<div><iframe src="child.htm"></iframe></div>
    
</body>
</html>

child.htm:

 

<html>  
<head>  
    
<meta  http-equiv='Content-Type'  content='text/html;  charset=gb2312' />  
    
<meta  name='author'  content='F.R.Huang(meizz梅花雪)//www.meizz.com' />  
    
<title>iframe  自適應其加載的網頁(多瀏覽器兼容)</title>  
    
<script type="text/javascript">
    
<!--
    
function iframeAutoFit()
    
{
        
try
        
{
            
if(window!=parent)
            
{
                
var a = parent.document.getElementsByTagName("IFRAME");
                
for(var i=0; i<a.length; i++//author:meizz
                {
                    
if(a[i].contentWindow==window)
                    
{
                        
var h1=0, h2=0, d=document, dd=d.documentElement;
                        a[i].parentNode.style.height 
= a[i].offsetHeight +"px";
                        a[i].style.height 
= "10px";

                        
if(dd && dd.scrollHeight) h1=dd.scrollHeight;
                        
if(d.body) h2=d.body.scrollHeight;
                        
var h=Math.max(h1, h2);

                        
if(document.all) {h += 4;}
                        
if(window.opera) {h += 1;}
                        a[i].style.height 
= a[i].parentNode.style.height = h +"px";
                    }

                }

            }

        }

        
catch (ex){}
    }

    
if(window.attachEvent)
    
{
        window.attachEvent(
"onload",  iframeAutoFit);
        
//window.attachEvent("onresize",  iframeAutoFit);
    }

    
else if(window.addEventListener)
    
{
        window.addEventListener(
'load',  iframeAutoFit,  false);
        
//window.addEventListener('resize',  iframeAutoFit,  false);
    }

    
//-->
    
</script>  
</head>  
<body>
    
<table border="1" width="200" style="height: 400px; background-color: yellow">
        
<tr>
            
<td>iframe  自適應其加載的網頁(多瀏覽器兼容:IE5.5+、Mozilla、Firefox、Opera、Netscape7.2+、Safari3等,支持XHTML)</td>
        
</tr>
    
</table>
</body>  
</html>

  很多人反應在IE7裏使用它會死機,那是因爲在自適應高度時觸發了 window.onresize 事件,而這個事件又去調用這個調整 <iframe> 高度的函數,產生了死循環調用。

  這段代碼裏我對 iframe 所在的父元素也設定了一個高度,以防止iframe 高度變化時頁面跳動的太厲害,在調用的時候可酌情使用這個設置。

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章