Javascript使iframe自适应高度

原创文章 作者:月光光 2015年08月04日 18:22helloweba.com 标签:JavaScript 

工作中我们遇到了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;
}

注意本文谈到的iframe自适应以及上一篇文章中的iframe操作dom都是基于同域下的操作,即在相同域名下实现的,那么如果在不同域名下即跨域是不能这样操作的。关于iframe跨域操作相关介绍请关注本站下一期文章介绍。

声明:本文为原创文章,helloweba.net和作者拥有版权,如需转载,请注明来源于helloweba.net并保留原文链接:https://www.helloweba.net/javascript/317.html

3条评论

  • 扶

    我想请问一下为什么我这行代码老是报错呢?var doc = ifrm.contentDocument? ifrm.contentDocument:ifrm.contentWindow.document; 这行好像.contentDocument就一直报错这是为什么啊?

  • 特意登录来给博主一个好评,搜了一早上,到现在才把这个问题解决了,强烈点赞,提前预祝春节快乐

  • 我需要定制个web系统,不知道博主有时间弄没有