iframe自适应高度(同域与跨域二种情况)

发布时间:2019-11-24编辑:脚本学堂
本文介绍下,在同域或跨域环境中,iframe自适应高度的实现方法,有需要的朋友,参考下吧。

1,同域下的iframe自适应高度
同域下父页面内的js能获取到iframe页面的高度,所以在iframe加载完后获取下高度就可以了。
 

复制代码 代码示例:
<iframe src="./ue.html" id="Iframe" frameborder="0" scrolling="no" style="border:0px;width:1000px;" onload="autoHeight();"></iframe>
<script type="text/javascript">
    function autoHeight(){
        var iframe = document.getElementById("Iframe");
        if(iframe.Document){//ie自有属性
            iframe.style.height = iframe.Document.documentElement.scrollHeight;
        }else if(iframe.contentDocument){//ie,firefox,chrome,opera,safari
            iframe.height = iframe.contentDocument.body.offsetHeight ;
        }
    }
</script>
 

如果是同一个域名下的不同子域,设置下document.domain就可以了。

IE6和IE7中的iframe没有contentDocument属性,而且如果iframe里的页面在同域下的不同子域,通过iframe.Document.documentElement.scrollHeight获取到的高度是错误的,所以还是建议用 iframe.contentwindow.document来获取高度。

2,跨域下的iframe自适应高度
跨域时,由于js的同源策略,父页面内的js不能获取到iframe页面的高度。需要一个页面来做代理。
方法如下:
假设www.a.com下的一个页面a.html要包含www.b.com下的一个页面c.html。
使用www.a.com下的另一个页面agent.html来做代理,通过它获取iframe页面的高度,并设定iframe元素的高度。

a.html中包含iframe:
 

复制代码 代码示例:
<iframe src="http://www.b.com/c.html" id="Iframe" frameborder="0" scrolling="no" style="border:0px;"></iframe>

在c.html中加入:
 

复制代码 代码示例:
<iframe id="c_iframe"  height="0" width="0"  src="http://www.a.com/agent.html" style="display:none" ></iframe>
<script type="text/javascript">
    (function autoHeight(){
        var b_width = Math.max(document.body.scrollWidth,document.body.clientWidth);
        var b_height = Math.max(document.body.scrollHeight,document.body.clientHeight);
        var c_iframe = document.getElementById("c_iframe");
        c_iframe.src='#'"
    })();
</script>

最后,agent.html中放入一段js:
 

复制代码 代码示例:
<script type="text/javascript">
    var b_iframe = window.parent.parent.document.getElementById("Iframe");
    var hash_url = window.location.hash;
    if(hash_url.indexOf("#")>=0){
        var hash_width = hash_url.split("#")[1].split("|")[0]+"px";
        var hash_height = hash_url.split("#")[1].split("|")[1]+"px";
        b_iframe.style.width = hash_width;
        b_iframe.style.height = hash_height;
    }
</script>
 

agent.html从URL中获得宽度值和高度值,并设置iframe的高度和宽度(因为agent.html在www.a.com下,所以操作a.html时不受JavaScript的同源限制)。

有关同域或跨域时,iframe自适应高度的实现方法与代码,就介绍完了,希望对大家有所帮助。