先附上代码,详细查看注释部分.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>iframe自适应高度</title>
<script type="text/javascript">
window.onload = (function () {
var iObj = document.getElementById('iframeDiv'); //iframe 的ID号
iObj.height = iObj.contentWindow.document.documentElement.scrollHeight; //contentWindow iframe的属性
});
</script>
</head>
<body>
<p>http://www.51jquery.com/2009-09/iframe-autoheight/</p>
<p>http://ued.koubei.com/?p=243</p>
<h2> iframe自适应</h2>
<p>1.如果 iframe 里面无许做 DOM 操作的话,我们可以在iframe里面直接 加一个事件 <pre>οnlοad="this.height=this.contentWindow.document.documentElement.scrollHeight" </pre></p>
<p>2.利用 iframe 的ID号 获取 iframe子页面的 contentWindow</p>
<p>3.在iframe页里进行DOM操作,或者表格展现(表格展现如果挤压会改变高度)可以使用下面的方法:</p>
<pre>
<code><script type="text/javascript">
function reinitIframe() {
var iframe = document.getElementById("iframe");
try {
var bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
var height = Math.max(bHeight, dHeight);
iframe.height = height;
} catch (ex) { }
}
window.setInterval("reinitIframe()", 200); //定时去检查iframe的高度,这样保证时时都是自动高了
</script>
</code>
</pre>
<div class="iframe" id="iframe" >
<iframe frameborder="1" scrolling="no" src="test1.html" name="iframe" id="iframeDiv" width="100%" height="100%">
</iframe>
</div>
</body>
</html>