天天看点

6种iframe高度自适应的方法

6种iframe高度自适应的方法

js自适应高度,实际上就是设置iframe的高度,设置等于内嵌网页的高度,从而看不到滚动条和嵌套痕迹。对于用户体验和网站美观起着重要作用。我们可以通过css来给它直接定义一个高度,同样可以实现上面的需求。当内容是未知或者是变化的时候。这个时候又有几种情况了。

1、iframe内容未知,高度可预测

这个时候,我们可以给它添加一个替换的css的min-height值,然后同时使用JavaScript改变高度。常用的兼容代码有:

// document.domain = "caibaojian.com";
function setIframeHeight(iframe) {
if (iframe) {
var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
if (iframeWin.document.body) {
iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
}
}
};


window.onload = function () {
setIframeHeight(document.getElementById('external-frame'));
};      

如果在同一个顶级域名下,不同子域名之间互通信息,设置document.domain =“ caibaojian.com”只要修改以上的iframe的ID就可以了。不污染html代码,建议使用上面的代码。

<iframe src="backtop.html" frameborder="0" scrolling="no" id="external-frame" onload="setIframeHeight(this)"></iframe>      

2、多个iframe的情况下

<script language="JavaScript">
//输入你希望根据页面高度自动调整高度的iframe的名称的列表
//用逗号把每个iframe的ID分隔. 例如: ["myframe1", "myframe2"],可以只有一个窗体,则不用逗号。
//定义iframe的ID
var iframeids=["test"];
//如果用户的浏览器不支持iframe是否将iframe隐藏 yes 表示隐藏,no表示不隐藏
var iframehide="yes";
function dyniframesize()
{
var dyniframe=new Array()
for (i=0; i<iframeids.length; i++)
{
if (document.getElementById)
{
//自动调整iframe高度
dyniframe[dyniframe.length] = document.getElementById(iframeids[i]);
if (dyniframe[i] && !window.opera)
{
dyniframe[i].style.display="block";
if (dyniframe[i].contentDocument && dyniframe[i].contentDocument.body.offsetHeight) //如果用户的浏览器是NetScape
dyniframe[i].height = dyniframe[i].contentDocument.body.offsetHeight;
else if (dyniframe[i].Document && dyniframe[i].Document.body.scrollHeight) //如果用户的浏览器是IE
dyniframe[i].height = dyniframe[i].Document.body.scrollHeight;
}
}
//根据设定的参数来处理不支持iframe的浏览器的显示问题
if ((document.all || document.getElementById) && iframehide=="no")
{
var tempobj=document.all? document.all[iframeids[i]] : document.getElementById(iframeids[i]);
tempobj.style.display="block";
}
}
}
if (window.addEventListener)
window.addEventListener("load", dyniframesize, false);
else if (window.attachEvent)
window.attachEvent("onload", dyniframesize);
else
window.onload=dyniframesize;
</script>      

3、针对知道的iframe的ID调用

function iframeAutoFit(iframeObj){
setTimeout(function(){if(!iframeObj) return;iframeObj.height=(iframeObj.Document?iframeObj.Document.body.scrollHeight:iframeObj.contentDocument.body.offsetHeight);},200)
}      

4、内容宽度变化的iframe高度自适应

<iframe src="backtop.html" frameborder="0" scrolling="no" id="test" onload="this.height=100"></iframe>
<script type="text/javascript">
function reinitIframe(){
var iframe = document.getElementById("test");
try{
var bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
var height = Math.max(bHeight, dHeight);
iframe.height = height;
console.log(height);
}catch (ex){}
}
window.setInterval("reinitIframe()", 200);
</script>      

5、跨域下的iframe自适应高度

跨域的时候,由于js的同源策略,父页面内的js无法获取到iframe页面的高度。需要一个页面来做代理。方法如下:假设www.a.com下一个一个页面a.html要包含我们使用www.a.com下一个另一个页面agent.html来做代理,通过它获取iframe页面的高度,并设置iframe元素的高度。html中包含iframe:

<iframe src="http://www.b.com/c.html" id="Iframe" frameborder="0" scrolling="no"></iframe>      

在c.html中加入如下代码:​

<iframe id="c_iframe"  height="0" width="0"  src="http://www.a.com/agent.html" ></iframe>
<script type="text/javascript">
(function autoHeight(){
var b_width = Math.max(document.body.scrollWidth,document.body.clientWidth);
var b_height = Math.max(document.body.scrollHeight,document.body.clientHeight);
var c_iframe = document.getElementById("c_iframe");
c_iframe.src = c_iframe.src + "#" + b_width + "|" + b_height;  // 这里通过hash传递b.htm的宽高
})();
</script>      

最后,agent.html中加入一段js:

<script type="text/javascript">
var b_iframe = window.parent.parent.document.getElementById("Iframe");
var hash_url = window.location.hash;
if(hash_url.indexOf("#")>=0){
var hash_width = hash_url.split("#")[1].split("|")[0]+"px";
var hash_height = hash_url.split("#")[1].split("|")[1]+"px";
b_iframe.style.width = hash_width;
b_iframe.style.height = hash_height;
}
</script>      

agent.html从URL中获得宽度值和高度值,并设置iframe的高度和宽度(因为agent.html在www.a.com下,所以操作a.html时不受JavaScript的类似限制)

6、postMessage + window.name实现跨域iframe高度自适应兼容版

我们知道HTML5 PostMessage不支持IE8以下的浏览器跨域,于是我想到了window.name支持ie6和ie7的方案,那么能否把这两种合并起来,变成一种全兼容的跨域方案呢?还别说,真有人能做到。

html5 postMessage实现跨域

postMessage是html5的一个新功能,可以实现不同域名之间的通信,通过给postMessage方式发送数据,监听则通过在父子窗口上添加onmessage事件进行。缺点也就很明显了,只有支持html5的浏览器才支持这种跨域方式,像IE6、7当然就拒之门外了!

window.name实现跨域

window.name实现跨域也是一个比较老的问题,之前kejun写过一个演示,可是给的却是同域名的通信。其实kejun的实例中就是实现跨域的,不过他采用了同一个域名,而且过程比较崎岖:

  1. 建立iframe,指定src为被跨域的页面
  2. 被跨域文件修改window.name,将数据传给window.name
  3. 将iframe.src修改为本域代理文件,然后就可以取到contentWindow.name
  4. 进行处理数据,清除iframe充分的运用了window.name因为页面的URL改变而名称不改变的特性。但是如果我们是自己用,还是可以的,而如果我们放出去要别人使用我们写的东西,那样学习成本太大。

多浏览器双向跨域

为了解决上面的问题,我们使用的方法就是如果支持postMessage的浏览器就使用postMessage,如果不支持的就采用window.name的方式,幸运的是在IE6、7中支持跨域设置window.name,而我们就可以简单的通过window.name来跨域。

然后建立计时器来监听window.name是否发生了变化,如果变化则接收并分析window.name,然后做请求。 

演示和代码:

<body>
  <div style="width:100%;border:1px solid green;">
    <h3>this page from :<span id="host"></span></h3>
    <input type="text" value="" id="data" /><button id="btn" onclick="send();">提交</button>
  </div>
  
  <iframe id="iframeA" src="http://1.qdemo.sinaapp.com/cross-domain/client.html" style="border:1px solid #ff6600;width:100%;height:300px;"></iframe>
  <script type="text/javascript">
    document.getElementById('host').innerHTML = location.host;
    function send(){
      var val = document.getElementById('data').value;
      sendMessage(val);
    }
    (function(win, doc){
      var ifr = doc.getElementById('iframeA').contentWindow;
      var cb = function(json){
        alert(location.host+" get msg:"+json);
      };
      var sendMessage = function(){
        if(win.postMessage){
          if (win.addEventListener) {
                    win.addEventListener("message",function(e){
            cb.call(win,e.data);
          },false);
                }else if(win.attachEvent) {
                    win.attachEvent("onmessage",function(e){
            cb.call(win,e.data);
          });
                }
          return function(data){
            ifr.postMessage(data,'*');
          };
        }else{
          var hash = '';
          
          setInterval(function(){
          
            if (win.name !== hash) {
              hash = win.name;
              cb.call(win, hash);
            }
          }, 50);
          return function(data){
            ifr.name = data;
          };
        }
      };
      win.sendMessage = sendMessage();
    })(window, document);
</script>
</body>      
<body>
  <h3>this page from :<span id="host"></span></h3>
  <input type="text" value="" id="data" /><button id="btn" onclick="send();">提交</button>
  <ul>
    <li>firefox、chrome等高级浏览器采用html5 postMessage方法</li>
    <li>IE6 7等使用window.name方法</li>
    <li>支持双向跨域,在chrome 13、firefox6、IE6+测试通过</li>
    <li>window.name可以通过data加随机数方式,避免两次提交的数据相同,本例没做处理,所以如果不改变value值点击提交是不会触发alert的</li>
    <li><a href="cross-domain.zip">demo下载</a></li>
  </ul>
  <script type="text/javascript">
    document.getElementById('host').innerHTML = location.host;
    function send(){
      var val = document.getElementById('data').value;
      sendMessage(val);
    }
    (function(win, doc){
      var ifr = win.parent;
      
      var cb = function(json){
        alert(location.host+"  get msg:"+json);
      };
      var sendMessage = function(){
        if(win.postMessage){
          if (win.addEventListener) {
                    win.addEventListener("message",function(e){
            cb.call(win,e.data);
          },false);
                }else if(win.attachEvent) {
                    win.attachEvent("onmessage",function(e){
            cb.call(win,e.data);
          });
                }


          return function(data){
            ifr.postMessage(data,'*');
          };
        }else{
          var hash = '';
          
          setInterval(function(){
            if(win.name!==hash){
              hash = win.name;
              cb.call(win,hash);
            }
          },50);
          return function(data){
            ifr.name = data;
          };
        }
      }
      win.sendMessage = sendMessage();
    })(window, document);
</script>
</body>      

基于上面的代码,结合我上篇文章的演示,我们再来命名一个iframe自适应高度的解决方案。

本文完〜

继续阅读