非静态化页面的iframe 自适应高度

On 2009年07月17日, in Javascript, by Kane

传统的iframe 自适应高度

<iframe id="frame_content" src="frame_content.html" scrolling="no" frameborder="0" onload="this.height=this.contentWindow.document.documentElement.scrollHeight"></iframe>

这种是针对 frame内容已静态输出了高度。而当frame页面有 dom 操作改变了页面高度的时候,怎么办?

参考了 口碑UED 的一片文章,使用的方法是setInterval 不断刷新frame框架页面,让frame内容页面高度改变时调整高度。 而为了避免影响性能,可以通过 iframe内的页面对dom操作改变了高度的时候,再去执行父级调整iframe高度。

最后代码:

<iframe id="frame_content" src="iframe_content.html" scrolling="no" frameborder="0" onload="this.height=this.contentWindow.document.documentElement.scrollHeight"></iframe>

<script type="text/javascript">

function reinitIframe(){

var iframe = document.getElementById("frame_content");

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);

</script>

<!--在iframe_contnet.html 页面,当对DOM操作的时改变了高度,就加入下面代码。 -->
window.parent.reinitIframe();
Tagged with:  

Leave a Reply