zoukankan      html  css  js  c++  java
  • iframe 自适应高度

    最近做到这样的项目,自己实现了一下

    场景是 跨域 子页面动态高度的

    自己的实现用到了 postMessage 和 跨域 代理 iframe  。

    参考了这篇博客的内容,记录一下,有空再完善一下具体方案。 

     每半秒钟检测一下子页面高度,是否有变化,如果变化发送信息到主域。

    it.e.addEventListener(window,'load',function(){
            
        it.winHeight = it.getHeight();
        try{postMsg('setHeight|'+it.winHeight);}catch(e){};    
        setInterval(function(){
                try{
                    if(it.winHeight != it.getHeight()){
                        it.winHeight = it.getHeight();
                        postMsg('setHeight|'+it.winHeight);
                        }else{
                            //console.log(it.winHeight)    
                            }
                    }catch(e){};
                },5E2);
                
            

            }); 

     postMsg 的实现:

     支持postMessage 的 调用postMessage 不支持的IE6 IE7 用iframe代理,通过调取主域下的js_proxy.html+search值 传输信息到主域。 

    function postMsg(msg) { 
      if(window.parent.postMessage) { 
         window.parent.postMessage(msg, hostDomain); 
      } else {
         // alert(msg);
        var proxy = hostDomain+'/js_proxy.html?',
            frame = document.getElementById('js_proxy');
        var clear = function(f){
                try{
                    f.contentWindow.document.write('');
                    f.contentWindow.close();
                    document.body.removeChild(frame);
                }catch(e){}
            }; 
        if(frame){
            clear(frame);
            };             
        frame = document.createElement('iframe');
            document.body.appendChild(frame);
            frame.id = "js_proxy"
            frame.style.display = 'none';
        frame.name = msg;
        frame.contentWindow.location = proxy+msg;
      }; 

     }; 

    接收数据和执行的实现:

     主域中的脚本,接收message

    if(window.postMessage) { 
      if(typeof window.addEventListener != 'undefined') { 
        window.addEventListener('message', onmessage, false); 
      } 
      else if(typeof window.attachEvent != 'undefined') { 
        window.attachEvent('onmessage', onmessage); 
      } 

    };

    主域下的js_porxy.html?msg  通过分析 location.search 来接收数据并处理。

     var hash = window.location.search.toString().substring(1);

            //alert('trance'+hash);
            var msg = hash,func = msg.split('|')[0] , parm = msg.split('|')[1];
             if(func == 'setHeight'){
                parent.parent.window.document.getElementById('thridparty').height = parm;
                };

     通过hash 也可以,但是 不知道为何在实现的时候 出现莫名其妙的hash被截断的情况,改用search解决。 

  • 相关阅读:
    IPv6隧道技术——6to4实验分析
    IPV6地址解析与DAD机制实验分析
    交换机的高级特性
    组播IGMP实验分析
    BGP实验分析(二)
    BGP实验分析(一)
    路由策略实验分析(二)
    路由策略实验分析(一)
    一线互联网拼多多、饿了么、蚂蚁金服、哈啰出行、携程、饿了么、2345、百度等一些Java面试题
    Java中的匿名内部类
  • 原文地址:https://www.cnblogs.com/trance/p/2345215.html
Copyright © 2011-2022 走看看