• [转载]跨域iframe高度自适应


    场景:

      经常会有这样的需求,跟外部合作伙伴合作,要嵌入别人的页面,这时候就需要高度自适应了,在这种跨域的情况下如何解决呢?

    解决:

       在iframe(合作伙伴的页面,称为P页面)中创建一个隐藏的iframe(称为M2页面),它的src与主页面(称为M1页面)同域,当P页面载入完成,计算出此页面的高度,然后创建隐藏iframe(M2页面),设置M2的src属性,将高度附加到M2的url后面,如http://localhost/proxy.html#height=582,代码:

     1 (function(){
     2     window.onload = function(){
     3         var w = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth),
     4         h = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight),
     5         body = document.getElementsByTagName('body')[0],
     6         iframe = document.createElement('iframe'),
     7         proxyUrl = 'http://hsz-15128:88/proxy.html#'+w+'|'+h;
     8          
     9         iframe.setAttribute('src', proxyUrl);
    10         iframe.style.width = '0';
    11         iframe.style.height = '0';
    12         iframe.style.borderWidth = '0';
    13         body.appendChild(iframe);
    14     }
    15 })();

     然后在proxy.html页面中添加如下代码

     1 (function(){
     2     window.onload = function(){
     3         var hash = self.location.hash,
     4             index = hash.indexOf('#'),
     5             datas = [],
     6             w, 
     7             h,
     8             piframe;
     9          
    10         if( index != -1){
    11             datas = hash.substr(index+1).split('|');
    12              
    13             w = datas[0];
    14             h = datas[1];
    15              
    16             piframe = parent.parent.document.getElementById('cross');
    17             piframe.style.width = w +'px';
    18             piframe.style.height = h + 'px';
    19              
    20         }
    21     }
    22 })();

    取得合作伙伴页面的高度并传给主页面,并重新设置主页面中iframe。

    以上代码在一次项目中亲测可用,感谢@达不留

    原文链接: http://my.oschina.net/forcoding/blog/67663?fromerr=T4ZnYlSh

  • 相关阅读:
    Spring_7_AOP之Advice应用
    JAVA豆知识
    SPRING事务_2
    JSP_5_JavaBean
    Spring事务_1
    java基本类型和包装类型
    SVN使用教程总结
    通过反射来创建对象?getConstructor()和getDeclaredConstructor()区别?
    Java泛型中extends和super的区别?
    数字签名、数字证书、对称加密算法、非对称加密算法、单向加密(散列算法)
  • 原文地址:https://www.cnblogs.com/djh-create/p/5004780.html
Copyright © 2020-2023  润新知