今天帮一个朋友解决iframe自动适应高度的问题,发现网上很多解决方案可以解决高度变大的问题,但当高度有大变到小的时候,则iframe的高度不变,经过不断搜索测试,发现下面一段代码有效。
其中的最小高度(红色字体部分)请各位根据自己的情况适应即可。
<script language="javascript">
function SetWinHeight(obj)
{
var win=obj;
obj.height=200;
if (document.getElementById)
{
if (win && !window.opera)
{
if (win.contentDocument && win.contentDocument.body.offsetHeight)
win.height = win.contentDocument.body.offsetHeight;
else if(win.Document && win.Document.body.scrollHeight)
win.height = win.Document.body.scrollHeight;
if(win.height < document.body.clientHeight)
win.height = document.body.clientHeight - 250;
}
}
}
</script>
<iframe id="top" name="top" marginwidth="0" marginheight="0" width="100%" height="180" src="title.htm" scrolling="no" frameborder="0"></iframe>
<iframe width="100%" align="center" height="200" id="main" name="main" οnlοad="Javascript:SetWinHeight(this)" frameborder="0" scrolling="no" src="main.htm"></iframe>
<iframe id="bottom" name="bottom" marginwidth="0" marginheight="0" width="100%" height="40" scrolling="no" src="copyright.htm" frameborder="0"></iframe>