如何动态调整iframe的高度

如何动态调整iframe的高度

假设你希望在你的网页添加一个子iframe,你当然就要调整它的大小以使它不出现滚动条。看,你想要的东西看起来是这样的:

这是达到目的的一个方法。首先,做一个你想嵌套的iframe。我做了一个如下的"child-frame.html":

<html>
<head> <title>Child frame</title> </head>
<body bgcolor=”#000000″>

<font color=”#ffffff”>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
</font>

</body>
</html>

然后,在父框架中,可以添加如下的代码:

<html>
<head> <title>Parent frame</title> </head>

<body onload=”resizeFrame(document.getElementById(’childframe’))” bgcolor=”#cccccc”>

<script type=”text/javascript”>
// Firefox worked fine. Internet Explorer shows scrollbar because of frameborder
function resizeFrame(f) {
f.style.height = f.contentWindow.document.body.scrollHeight + “px”;
}
</script>

<p>Parent frame.</p>
<p>Parent frame.</p>
<p>Parent frame.</p>
<p>Parent frame.</p>

<p>
<iframe frameborder=0 border=0 src=”./child-frame.html” name=”childframe” id=”childframe”>
</iframe>
</p>

</body>
</html>

你同样也能看到一个动态调整iframe高度的实例

这些代码是干什么用的呢?当导入父框架的高度时,它会查询文件中与iframe相一致的"childframe"元素,然后页面调用resizeFrame()功能。这项功能将frame的高度设定为 scrollHeight,这样就能有效的删除滚动条。

唯一棘手的一点就是框架中"frameborder=0 border=0"的属性。如果你去掉frameborder 属性,Internet Explorer浏览器将假定这个框架有一个非零边框,但它并不会包含在返回给scrollHeight的frameborder值中。最终的效果还是会显示出一个滚动条,除非你添加属性:"frameborder=0".


您或许还对以下的内容感兴趣: