当前位置:编程学习 > asp >>

Ifram框架自适应内容的高度(代码简单易懂ie7,8,9,火狐,谷歌都测试通过)

Ifram框架自适应内容的高度这个是长期困扰我的一个问题,今天有时间又把之前的代码拿出来研究了下,刚好最近我在做一个项目,经常用到JQ的写法,举一反三,让我找到了方法:

 


这个是之前网上找的,只能支持IE7:代码如下

<script language="javascript">
        function SetCwinHeight()//自动拉伸
        {
            var xsun = document.getElementById("main"); //iframe id
            if (document.getElementById) {
                if (xsun && !window.opera) {
                    if (xsun.contentDocument && xsun.contentDocument.body.offsetHeight) {
                        xsun.height = xsun.contentDocument.body.offsetHeight + 20;
                    } else if (xsun.Document && xsun.Document.body.scrollHeight) {
                        xsun.height = xsun.contentDocument.body.offsetHeight + 20;
                    }
                }
            }
        }
    </script>

 


我修改后的代码:

<script language="javascript">
        function SetCwinHeight()//自动拉伸
        {
            var xsun = document.getElementById("main"); //iframe id
            //var h1 = xsun.contentDocument.body.offsetHeight;
            var h2 = document.documentElement.offsetHeight;
            if (document.getElementById) {
                if (xsun && !window.opera) {
                    if (xsun.contentDocument && h2) {
                        xsun.height = h2 + 20;
                    } else if (xsun.Document && xsun.Document.body.scrollHeight) {
                        xsun.height = h2 + 20;
                    }
                }
            }
        }
    </script>

应该能很清楚的看到区别在哪里,就是var h1 = xsun.contentDocument.body.offsetHeight;
                                                                    var h2 = document.documentElement.offsetHeight;

h1取出来的高度都为0,h2才是正确高度。具体含义自己去百度下就知道两者的区别了

调用方法:

<iframe frameborder="0" id="main" name="main" onload="javascript:SetCwinHeight();"
                        src="xsun.html" marginwidth="0" marginheight="0" scrolling="no" style="z-index: 1;
                        width: 100%; min-height: 300px;"></iframe>

 

 

 

补充:Web开发 , ASP.Net ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,