让iframe自适应高度 兼容多种浏览器随着窗口大小改变

来源:互联网 发布:守望先锋查看队友数据 编辑:程序博客网 时间:2024/05/29 10:07

工作中我们遇到了iframe嵌入页面高度自适应的问题。因为我们不知道所加载的iframe内容页面会有多高,又不想在页面上出现难看的滚动条,这个时候我们可以使用Javascript来动态让iframe自适应高度。

我们准备一个主页面a.html,以及两个用于嵌入iframe的页面分别为iframeH.html和iframeH1.html,内容可以自己随便加,实际应用中可能是后台生成的内容。

为了演示,我们在主页面a.html中加入如下代码:

<div class="opt_btn"> 
    <button onclick="getData('iframeH');">加载内容1</button> 
    <button onclick="getData('iframeH2');">加载内容2</button> 
</div> 
<iframe src="iframeH.html" id="ifrm" frameborder="0" width="100%" scrolling="no" marginheight="0" marginwidth="0" onLoad="setIframeHeight(this.id)"></iframe> 

我们要实现的是,分别点击两个按钮,iframe中加载不同的内容,iframe中不能出现滚动条。

Javascript

首先我们使用Javascript动态改变iframe的src值,即分别点击两个按钮时,iframe加载不同的页面内容。代码中按钮button分别调用了自定义函数getData()就实现了切换内容的效果。

function getData(ifm){ 
    document.getElementById("ifrm").src = ifm+'.html'
} 

然后,我们来关注iframe里的内容,因为我们事先不知道iframe的内容高度,如果先设置好iframe的高度height值,很可能当页面内容超长时会出现滚动条,这不是我们想要的。那么我们使用Javascript来动态获取iframe页面高度,然后设置iframe的高度。

在iframe完全加载后即onload,调用setIframeHeight(),iframe内容加载完成后,可获取iframe的高度值,然后重新设置iframe的高度,以下是整理好的代码:

function setIframeHeight(id) { 
    var ifrm = document.getElementById(id); 
    var doc = ifrm.contentDocument? ifrm.contentDocument:  
        ifrm.contentWindow.document; 
    ifrm.style.visibility = 'hidden'
    ifrm.style.height = "10px"// reset to minimal height ... 
    ifrm.style.height = getDocHeight( doc ) + 4 + "px"
    ifrm.style.visibility = 'visible'
} 
 
function getDocHeight(doc) { 
    doc = doc || document; 
    var body = doc.body, html = doc.documentElement; 
    var height = Math.max( body.scrollHeight, body.offsetHeight,  
        html.clientHeight, html.scrollHeight, html.offsetHeight ); 
    return height; 
} 
0 0