JavaScript实现Iframe自适应内容高度(多浏览器兼容)

作者:交互手记时间:2026-10-31 02:55:42浏览:219

本文提供一段JavaScript代码,用于实现Iframe根据加载内容自动调整高度。通过遍历页面中的IFrame元素并获取body的scrollHeight,结合针对IE和Opera浏览器的像素修正值,实现高度自适应。代码包含异常处理以应对跨域操作限制,并兼容不同事件绑定方式,适用于需要嵌入外部页面且希望保持版面整洁的场景。

main.htm: 

Iframe自适应高度实现代码

示例代码:

<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>


作者最新文章