iframe自适应高度计算-兼容低版本IE以及各浏览器

 Html5并没有真正的废弃iframe标签,还是能够使用iframe标签的。当然利用jQuery的load也能实现iframe 所实现的。但现如今还没有更好的标签替代,frame使用起来很简单。虽然它会阻塞页面渲染,可以利用一个延时函数setTimeout(function() {}, 10);

或者一个load绑定事件:window.addEventListener('load', function() {});去避免页面阻塞。当然也会有其他跟好的方法。我不建议使用过多的iframe但不反对用,合理的运用不失为一种良策。

 

1.原生javascript方法:

  

 1 <iframe id="iframeId" name="content" src="" width="500" visibility="hidden" frameborder="0" onload="adaptiveFrameHeight()"></iframe>
 2 
 3 
 4 function adaptiveFrameHeight() { 
 5             var iframeId = document.getElementById("iframeId"); 
 6             var icd =iframeId.contentWindow.document ? iframeId.contentWindow.document : iframeId.contentDocument; 
 7             iframeId.style.visibility = 'hidden';
 8             iframeId.style.height = "10px";
 9             icd = icd || document; 
10             var height = Math.max( icd.body.scrollHeight, icd.body.offsetHeight,icd.documentElement.clientHeight, icd.documentElement.scrollHeight, icd.documentElement.offsetHeight ); 
11             iframeId.style.height = height + "px"; 
12             iframeId.style.visibility = 'visible';
13         } 

 

 

1.jQuery实现方法:

  

1 <iframe id="iframeId" name="content" src="" width="500" visibility="hidden" frameborder="0"></iframe>
2 
3 $(function() {
4             $("#iframeId").load(function() {
5                 var height = $(this).contents().find("body").height()+20;
6                 $(this).height(height);
7           });
8         });

 

posted @ 2017-08-04 11:17  Missing_MBR  阅读(401)  评论(0编辑  收藏  举报