`
newpeter
  • 浏览: 38690 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

Iframe高度随内容自动调节

阅读更多

方式一:在被嵌入页里写入代码
假设main.htm文件内容:
    <iframe src="iframe.htm"></iframe>
则在iframe.htm文件中加入如下代码:
    <script language="JavaScript">
    <!--
    function window.onload() { 
        if(top.location != self.location){ 
            var a = window.parent.document.getElementsByTagName('iframe'); 
            for (var i=0; i<a.length; i++){ 
                if (a[i].name == self.name) {
                    a[i].height = document.body.scrollHeight+10; return;
                }
            }
        } 
    }
    // -->
    </script>
要测试效果则在iframe.htm文件中再加入一个表格(表格高度设大些):
    <table width="100%" height="1000"><tr><td valign="bottom">Hello!</td></tr></table>

用浏览器打开mail.htm就可以预览效果。

方式二:在父页中加入代码,被嵌入页不变(有两种方法)
一法:

在父页中加入如下代码:
<script language="Javascript">
var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
//extra height in px to add to iframe in FireFox 1.0+ browsers
var FFextraHeight=getFFVersion>=0.1? 16 : 0 

function dyniframesize(iframename) {
var pTar = null;
if (document.getElementById){
    pTar = document.getElementById(iframename);
}
else{
    eval('pTar = ' + iframename + ';');
}
if (pTar && !window.opera){
    //begin resizing iframe
    pTar.style.display="block"
    
    if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight){
      //ns6 syntax
      pTar.height = pTar.contentDocument.body.offsetHeight+FFextraHeight; 
    }
    else if (pTar.Document && pTar.Document.body.scrollHeight){
      //ie5+ syntax
      pTar.height = pTar.Document.body.scrollHeight;
    }
}
}
</script>
<iframe id="myTestFrameID" onload="javascript:{dyniframesize('myTestFrameID');}" marginwidth=0 marginheight=0 frameborder=0 scrolling=nosrc="myiframe.htm" width=200 height=100></iframe>

然后myiframe.htm中为正常页面内容。

用浏览器打开父页即可看到效果,该方法对各种浏览器通用,包括IE、FF、Opera等。

二法:
在父页中写入以下代码:
<iframe id=headlogin marginWidth=0 marginHeight=0 src="myiframe.htm" frameBorder=0 width=100% scrolling=no height=25onload="this.height=this.contentWindow.document.body.scrollHeight"></iframe> 

用浏览器打开父页即可看到效果。以上JScript代码在opera下不能正常显示出效果。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics