您好,欢迎来到途锐财经网。
搜索
您的当前位置:首页关于iframe嵌套子页面(含iframe)自动扩高的详解

关于iframe嵌套子页面(含iframe)自动扩高的详解

来源:途锐财经网


公司网站后台原本不是用iframe设计的,后来为了节约资源,经过讨论决定把网站后台改成iframe。iframe可以实现和ajax相似的 局部刷新的效果(他们的实现原理是不同的),iframe虽然很强大,但其不能根据子页面的高度自动扩高,这点很恼人啊,于是我在网上搜了搜,找到以下几种方法,然后进行部分改进了。

一、jquery获得(注意:此种方法只适合 父类页面和子类页面在同一个域名下,并且子类页面不能包含iframe)

aa.html(父及页面)

<iframe name="rightcontent" id="rightcontent" src='bb.html' frameborder="0" width="100%" scrolling="no"></iframe>

$("#rightcontent").load(function(){
 var mainheight = $(this).contents().find("body").height()+30;
 $(this).height(mainheight);
 });

二、用js获得(网上js获得的方法很多,随便一搜就可以找到,但需要注意的是:子类页面不能包含iframe,如果子类页面中有ifrme,还是不能实现自动扩高的效果的)

function SetCwinHeight(obj) {
 var cwin = obj;
 if (document.getElementByIdx_x_x_x) { 
 if (cwin && !window.opera) {
 if (cwin.contentDocument && cwin.contentDocument.body.offsetHeight){
 cwin.height = cwin.Document.body.offsetHeight + 30;
 alert(cwin.height); //FF NS
 }else if (cwin.Document && cwin.Document.body.scrollHeight){
 cwin.height = cwin.Document.body.scrollHeight + 10;
 } //IE
 }else {
 this.height=rightcontent.document.body.scrollHeight+30
 if (cwin.contentWindow.document && cwin.contentWindow.document.body.scrollHeight)
 cwin.height = cwin.contentWindow.document.body.scrollHeight; //Opera
 }
 }
}

<iframe name="rightcontent" id="rightcontent" src='bb.html' frameborder="0" width="100%" scrolling="no" onload="SetCwinHeight(this)">
</iframe>

三、支持子类页面中 包含iframe,即iframe嵌套使用(火狐和ie测试,其他浏览器还没测试)

 <iframe name="rightcontent" id="rightcontent" src='bb.html' frameborder="0" width="100%" scrolling="no" onload="this.height=rightcontent.document.body.scrollHeight+50"></iframe>

四、这个是补充的,网站用了方法三,但是发现如果如果牵扯到跨域名了,方法三不起作用了,是因为我在子页面中 写了 <script type="text/javascript">document.domain = 'xxx.com';</script>,这种情况下怎么办呢,代码如下:

在子页面中

<script type="text/javascript">
//设置域信息
document.domain = 'xxx.com';
//设置父级页面引用自身的iframe高度
function setHeight(){
 //判断是否为顶级页面
 if(window.top!=window.self){
 parent.document.getElementByIdx_x('rightcontent').height=document.body.scrollHeight+20
 }
}
setHeight();
</script>

Copyright © 2019- truthgptcn.cn 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务