JavaScript应用:Iframe自适应其加载的内容高度

来源:互联网 发布:致远工科荣誉计划知乎 编辑:程序博客网 时间:2024/04/30 14:12

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>
        <iframe src="child.htm"></iframe>
    </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  language=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 h = document.body.scrollHeight;
                   if(document.all) {h += 4;}
                   if(window.opera) {h += 1;}
                   a[i].style.height = h;
               }
            }
         }
      }
      catch (ex)
      {
         alert("脚本无法跨域操作!");
      }
   }
   if(document.attachEvent)  window.attachEvent("onload",  iframeAutoFit); 
   else  window.addEventListener('load',  iframeAutoFit,  false); 
   </script> 
</head> 
<body> 
   <div  style="width:  200;  height:  400;  background-color:  yellow"> 
       iframe  自适应其加载的网页(多浏览器兼容) 
   </div> 
</body> 
</html>

转自:http://blog.csdn.net/meizz/archive/2006/03/27/639857.aspx

原创粉丝点击