• iframe获取子页面高度(跨域)解决方案



    需求:A域名下 index2.html 使用iframe嵌套 B域名下 index2.html  ,通过B域名下页面高度,来控制A域名下iframe的高度。  简单说就是:跨域条件下,A页面使用iframe嵌套B页面,通过B页面的高度,来控制A页面iframe的高度。

    图中描述很形象,一共需要创建3个页面,来实现此功能;

    操作:
    为了区分域名,A域名下为A.com  B域名为B.com

    1.创建A域名下index2.html页面 ,即创建iframe,引入B域名下访问地址

      HTML:

      <div>
        <iframe id="test12" src="https://B.com/test2/index2.html" width="100%" height="200px" frameborder="no" border="0" marginwidth="0" marginheight="0" ></iframe>
      </div>

    2.创建B域名下index2,html页面 , 需要引入A域名下index3.html(引入一个div,方便显示高度,iframe不设置高度了。)

      HTML:

      <div style="height:500px;">
      </div>
      <iframe id="iframe" src="https://A.com/test2/index3.html" width="0" height="0"></iframe>

      JS:

      function sethash(){
        //判断浏览器兼容性
        var explorer = window.navigator.userAgent ;
        if(explorer.indexOf("Chrome") >= 0){
          hashH = document.documentElement.scrollHeight; //获取自身高度
        }else{
          hashH=document.body.scrollHeight;
        }
        urlC = "https://A.com/test1/index3.html"; //设置iframeA的src
        document.getElementById("iframe").src=urlC+"?height="+hashH; //将高度作为参数传递
      }
      window.onload=sethash;

    3.创建A域名下index3.html,根据B域名传递高度,设置A域名下index2.html下iframe高度(同域名下,可设置)

      JS:

      function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null)
          return unescape(r[2]);
        return null;
      }
      function pseth() {
        var iObj = window.parent.parent.document.getElementById('iframe');//A和main同域,所以可以访问节点
        window.parent.parent.document.getElementById("test12").setAttribute("height", getQueryString("height") + "px");
      }
      pseth();

    总结:

      iframe跨域的问题,实际是A嵌套B嵌套C,B传递给C,AC为同一域名下,可以进行操作。将C获取到B传递的值,赋值给A作为iframe的高度。

    资料参数:https://www.iteye.com/blog/imalex163-2183338

  • 相关阅读:
    JS浅拷贝和深拷贝
    使用阿里云短信服务
    autojs相关的文档地址记录和简单使用
    Linux 根目录所在分区被脏数据占满
    openstack宿主机故障,虚拟实例恢复
    openstack创建vlan网络并配置网络设备
    联想 lenove 3750 M4服务器更改启动项和管理口IP
    ansible常用方法
    Mysql数据库-多实例主从复制-主从故障详解
    Linux 系统优化-workstation实践
  • 原文地址:https://www.cnblogs.com/Yzzzzzzzzz/p/16229035.html
Copyright © 2020-2023  润新知