Ifram框架自适应内容的高度(代码简单易懂ie7,8,9,火狐,谷歌都测试通过)
ifram框架自适应内容的高度这个是长期困扰我的一个问题,今天有时间又把之前的代码拿出来研究了下,刚好最近我在做一个项目,经常用到jq的写法,举一反三,让我找到了方法:
这个是之前网上找的,只能支持ie7:代码如下
<script language="javascript">
function setcwinheight()//自动拉伸
{
var xsun = document.getelementbyid("main"); //iframe id
if (document.getelementbyid) {
if (xsun && !window.opera) {
if (xsun.contentdocument && xsun.contentdocument.body.offsetheight) {
xsun.height = xsun.contentdocument.body.offsetheight + 20;
} else if (xsun.document && xsun.document.body.scrollheight) {
xsun.height = xsun.contentdocument.body.offsetheight + 20;
}
}
}
}
</script>
我修改后的代码:
<script language="javascript">
function setcwinheight()//自动拉伸
{
var xsun = document.getelementbyid("main"); //iframe id
//var h1 = xsun.contentdocument.body.offsetheight;
var h2 = document.documentelement.offsetheight;
if (document.getelementbyid) {
if (xsun && !window.opera) {
if (xsun.contentdocument && h2) {
xsun.height = h2 + 20;
} else if (xsun.document && xsun.document.body.scrollheight) {
xsun.height = h2 + 20;
}
}
}
}
</script>
应该能很清楚的看到区别在哪里,就是var h1 = xsun.contentdocument.body.offsetheight;
var h2 = document.documentelement.offsetheight;
h1取出来的高度都为0,h2才是正确高度。具体含义自己去百度下就知道两者的区别了
调用方法:
<iframe frameborder="0" id="main" name="main" onload="javascript:setcwinheight();"
src="xsun.html" marginwidth="0" marginheight="0" scrolling="no" style="z-index: 1;
width: 100%; min-height: 300px;"></iframe>