iframe自适应高度问题

我页面中的iframe

<iframe name="mainFrame" id="mainFrame" src="/account/${pageName}"  width="100%" height="100%"
                        frameborder=0 marginheight="0" marginwidth="0"  scrolling="no"></iframe>

一共试了三种,目前感觉最好的一种:

<script>
   $(function(){
      $("#mainFrame").load(function(){
         var mainheight = $(this).contents().find("body").height()+10;
         $(this).height(mainheight);
      });
   });
</script>

 

参考:http://www.cnblogs.com/luluping/archive/2009/04/17/1437843.html

第二种: 问题:高度只可以增加不能减小

<script type="text/javascript">
    function iFrameHeight() {
        var ifm = document.getElementById("accountIndexIframe");
        var subWeb = document.frames ? document.frames["accountIndexIframe"].document : ifm.contentDocument;
        if(ifm != null && subWeb != null) {
            ifm.height = subWeb.body.scrollHeight;
//          ifm.width = subWeb.body.scrollWidth;
         }
   }
</script>

参考:http://www.cnblogs.com/Nbge/archive/2013/06/14/3135697.html

第三种:问题 使用的时候出现不顺畅的情况,点击第一次会失效,第二次才有用

<script type="text/javascript">
    var browserVersion = window.navigator.userAgent.toUpperCase();
    var isOpera = false, isFireFox = false, isChrome = false, isSafari = false, isIE = false;
    function reinitIframe(iframeId, minHeight) {
        try {
             var iframe = document.getElementById(iframeId);
             var bHeight = 0;
             if (isChrome == false && isSafari == false)
                    bHeight = iframe.contentWindow.document.body.scrollHeight;
             var dHeight = 0;
             if (isFireFox == true)
                  dHeight = iframe.contentWindow.document.documentElement.offsetHeight + 2;
             else if (isIE == false && isOpera == false)
                  dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
             else if (isIE == true && ! -[1, ] == false) { } //ie9+
             else
                  bHeight += 3;

             var height = Math.max(bHeight, dHeight);
             if (height < minHeight) height = minHeight;
                  iframe.style.height = height + "px";
         } catch (ex) { }
     }
function startInit(iframeId, minHeight) { isOpera = browserVersion.indexOf("OPERA") > -1 ? true : false; isFireFox = browserVersion.indexOf("FIREFOX") > -1 ? true : false; isChrome = browserVersion.indexOf("CHROME") > -1 ? true : false; isSafari = browserVersion.indexOf("SAFARI") > -1 ? true : false; if (!!window.ActiveXObject || "ActiveXObject" in window) isIE = true; window.setInterval("reinitIframe('" + iframeId + "'," + minHeight + ")", 100); } startInit('mainFrame', 500);//开始调用 </script>

出自:http://www.cnblogs.com/slyzly/articles/2422737.html

 

posted @ 2016-04-22 17:05  雨吃草  阅读(616)  评论(0编辑  收藏  举报