JavaScript Iframe 自动适应
场景:Iframe嵌入flash,希望flash能随着页面的resize而resize。
主要代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> New Document </title> <meta name="Generator" content="EditPlus"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <script type="text/javascript" src="/lrm-suite/js/jquery-2.0.3.js"></script> <script type="text/javascript"> var rpUrl = 'http://172.20.31.18:8080/lrm-suite/rp.xhtml'; function setAppFrameUrl(selectedUrl) { if ($.isReady) { activeUrl = selectedUrl; $('#appFrame' ).setAttribute('src', selectedUrl); } else { setTimeout(function() { setAppFrameUrl(selectedUrl); }, 100); } } function setNewActive(imgComp,urlName,imageSrc){ setAppFrameUrl(urlName); imgComp.src = imageSrc; } $(document).ready(function(){ $(window).resize(resizeframe); }); function resizeframe() { var margin-top = $('#appFrame' ).css( "margin-top" ); var topNum = margin-top.toString().slice(0,margin-top.length-2); var actualHeight = document.body.offsetHeight - topNum; $('#appFrame').css('height', actualHeight); } </script> </head> <body> <div class="topMenuBar" id="topMenuBarDiv" style="z-index: 999999"> <a id="j_idt8"> <img src="/lrm-suite/images/Logo.png" alt="" style="float: left; border: 0; cursor: pointer;" onclick="setNewActive(this,rpUrl,'/lrm-suite/images/Logo.png');"/> </a> . . . . </div> <iframe id="appFrame" style="border: 0; width: 100%; position: absolute; top: 0; left: 0; margin-top: 43px;" src="" scrolling="auto" frameborder="0" onload="resizeframe()"> </iframe> </body> </html>
分析:
首先导入JQuery框架,并设置iframe的scrolling=“auto”,这样的话可以自动的出现滚动条。
然后添加window的resize事件
$(document).ready(function(){ $(window).resize(resizeframe); }); function resizeframe() { var margin-top = $('#appFrame' ).css( "margin-top" ); var topNum = margin-top.toString().slice(0,margin-top.length-2); var actualHeight = document.body.offsetHeight - topNum; $('#appFrame').css('height', actualHeight); }
这样的话,每次浏览器resize的话,都会对iframe重新设置height,从而得到iframe resize的效果。
后来有人给出了一个另外的解决方案,跟这个原理类似,也贴出来以供参考。
var suiteVisible = true; function resizeIframe() { var el = document.getElementById("appFrame"); if (suiteVisible) { el.style.height = (document.body.clientHeight - 43) + "px"; } else { el.style.height = (document.body.clientHeight) + "px"; } } $(window).resize(function() { if (this.resizeTO) clearTimeout(this.resizeTO); this.resizeTO = setTimeout(function() { $(this).trigger('resizeEnd'); }, 500); }); $(window).bind('resizeEnd', function() { resizeIframe(); });
相关推荐
架构技术交流 2020-07-28
haohong 2020-07-18
tiankele0 2020-06-26
xiangxiaojun 2020-06-25
pythonclass 2020-06-04
WebVincent 2020-06-03
sixthelement 2020-05-30
云之高水之远 2020-05-19
云之高水之远 2020-05-17
Chydar 2020-05-15
tuxlcsdn 2020-04-17
ajaxtony 2020-02-03
STPace 2020-02-03
学留痕 2013-05-11
云之高水之远 2020-01-05
TONIYH 2019-12-20
nimeijian 2019-12-15
我只是个程序员 2014-01-18