iframe高度自动适应

      最近在用iframe嵌套页面,可是由于页面高度不一样,显示就不美观了!后来同事在网上找了很久,终于找到了解决办法,我在这里记录下,以便日后查看。

     1.非跨域实现

        有A.html和B.html两个页面,A.html中引入B.html:如:

       <iframe widht="100%" frameborder="0" scrolling="no" src="B.html" οnlοad="this.height=Math.max(this.windowContent.document.body.scrollHeight,this.windowContent.document.documentElement.scrollHeight)+10"><iframe>

注:有些浏览器不支持boby,所以就改成documentElement了

 

     2.跨域实现

       有A.html 、B.html、 C.html三个页面,A.htm和B.html不同域

如:http://www.baidu.com/A.html

      http://www.google.com/B.html

实现A.html 嵌入B.html,在可以操作B.html的情况下,引入一个中介页面C.html

(1)A.html中引入:

  <iframe width="0" height="0" frameborder="0" scrolling="no" src=" http://www.google.com/B.html" id="frame_content"></iframe>

(2)B.html中引入:

  <script type="text/javascript">

if(window.top!=window.self){ //判断当前窗口是不是顶层窗口,换句话说,判断当前窗口有没有被嵌套到其他窗口中,如果没,就是顶层窗口

document.write('<iframe src="" width="0" height="0" frameborder="0" scrolling="no" style="display:none" id="frameC"></iframe>');

window.οnlοad=function(){

var hsahH=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)+10;

var urlC=http://www.baidu.com/C.html;

var url=urlC+"#"+hashH;

document.getElementById("frameC").src=url;

}

}

</script>

(3)C.html引入

<script type="text/javascript">

function fn(){

var iObj=document.getElementById("frame_content");

if(iObj){

var hObj=window.location.hash;

if(iObj && hObj.indexOf("#")!=-1){

var hei=hObj.split("#")[1];

if(hei!=""){

iObj.style.height=hei+"px";

}

}

}

}

fn();

</script>

      原理:

          A.html与B.html不是同一个域,所以不能获取到B.html的高度

         B.html嵌入C.html,把高度传给它;

         这样由于C.html与A.html是同域,故A.html就可以获取到B.html的高度了;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值