iframe自适应高度完美版解决DOM元素高度变化问题

来源:http://www.sosuo8.com/article/show.asp?id=2917

如果iframe里面内容不进行DOM操作,可以使用这种最简单的方式:

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


反之,在iframe页里进行DOM操作,或者表格展现(表格展现如果挤压会改变高度)可以使用下面的方法 

JavaScript复制代码
  1. <iframe id="iframe" src="iframe_b.html" scrolling="no" frameborder="0"></iframe>
    <script type="text/javascript">       
  2. function reinitIframe() {           
  3.      var iframe = document.getElementById("iframe");           
  4.      try {               
  5.             var bHeight =iframe.contentWindow.document.body.scrollHeight;               
  6.             var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;              
  7.             var height = Math.max(bHeight, dHeight);            iframe.height = height;           
  8.         } catch (ex) { }       
  9. }       
  10. window.setInterval("reinitIframe()", 200);//定时去检查iframe的高度,这样保证时时都是自动高了
  11. </script>
posted @ 2013-05-10 17:12  hasayaki  阅读(413)  评论(0编辑  收藏  举报