首页 文章

调整iframe的宽度和高度以适应其中的内容

提问于
浏览
256

我需要 auto-adjusting widthheightiframe 解决方案,几乎不符合其内容 . 关键是在加载 iframe 之后可以更改宽度和高度 . 我想我需要一个事件动作来处理iframe中包含的主体尺寸的变化 .

27 回答

  • 43
    <script type="application/javascript">
    
    function resizeIFrameToFitContent( iFrame ) {
    
        iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
        iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
    }
    
    window.addEventListener('DOMContentLoaded', function(e) {
    
        var iFrame = document.getElementById( 'iFrame1' );
        resizeIFrameToFitContent( iFrame );
    
        // or, to resize all iframes:
        var iframes = document.querySelectorAll("iframe");
        for( var i = 0; i < iframes.length; i++) {
            resizeIFrameToFitContent( iframes[i] );
        }
    } );
    
    </script>
    
    <iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>
    
  • 5

    跨浏览器jQuery plug-in .

    Cross-bowser,跨域 library ,使用 mutationObserver 保持iFrame大小与内容相关, postMessage 在iFrame和主页之间进行通信 . 使用或不使用jQuery .

  • 2

    所有人都无法使用上述方法 .

    JavaScript的:

    function resizer(id) {
            var doc = document.getElementById(id).contentWindow.document;
            var body_ = doc.body, html_ = doc.documentElement;
    
            var height = Math.max(body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight);
            var width = Math.max(body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth);
    
            document.getElementById(id).style.height = height;
            document.getElementById(id).style.width = width;
    
        }
    

    HTML:

    <div style="background-color:#b6ff00;min-height:768px;line-height:inherit;height:inherit;margin:0px;padding:0px;overflow:visible" id="mainDiv"  >
             <input id="txtHeight"/>height     <input id="txtWidth"/>width     
            <iframe src="head.html" name="topFrame" scrolling="No" noresize="noresize" id="topFrame" title="topFrame" style="width:100%; height: 47px" frameborder="0"  ></iframe>
            <iframe src="left.aspx" name="leftFrame" scrolling="yes"   id="Iframe1" title="leftFrame" onload="resizer('Iframe1');" style="top:0px;left:0px;right:0px;bottom:0px;width: 30%; border:none;border-spacing:0px; justify-content:space-around;" ></iframe>
            <iframe src="index.aspx" name="mainFrame" id="Iframe2" title="mainFrame" scrolling="yes" marginheight="0" frameborder="0" style="width: 65%; height:100%; overflow:visible;overflow-x:visible;overflow-y:visible; "  onload="resizer('Iframe2');" ></iframe>
    </div>
    

    环境:IE 10,Windows 7 x64

  • 2

    到目前为止给出的所有解决方案仅考虑一次性调整大小 . 您提到您希望能够在修改内容后调整iFrame的大小 . 为了做到这一点,你需要在iFrame中执行一个函数(一旦内容被更改,你需要触发一个事件来说明内容已经改变) .

    我被困了一段时间,因为iFrame中的代码似乎仅限于iFrame中的DOM(并且无法编辑iFrame),并且在iFrame外部执行的代码被困在iFrame外部的DOM(并且没有'拿起来自iFrame内部的活动) .

    解决方案来自于发现(通过同事的帮助)可以告诉jQuery使用什么DOM . 在这种情况下,父窗口的DOM .

    因此,像这样的代码可以满足您的需求(在iFrame中运行时):

    <script type="text/javascript">
        jQuery(document).ready(function () {
            jQuery("#IDofControlFiringResizeEvent").click(function () {
                var frame = $('#IDofiframeInMainWindow', window.parent.document);
                var height = jQuery("#IDofContainerInsideiFrame").height();
                frame.height(height + 15);
            });
        });
    </script>
    
  • 6

    如果iframe内容来自同一个域,那么这应该很有用 . 它确实需要jQuery .

    $('#iframe_id').load(function () {
        $(this).height($(this).contents().height());
        $(this).width($(this).contents().width());
    });
    

    要让它动态调整大小,您可以这样做:

    <script language="javaScript">
    <!--
    function autoResize(){
        $('#themeframe').height($('#themeframe').contents().height());
    }
    //-->
    </script>
    <iframe id="themeframe" onLoad="autoResize();" marginheight="0" frameborder="0" src="URL"></iframe>
    

    然后在iframe加载的页面上添加:

    <script language="javaScript">
    function resize()
    {
        window.parent.autoResize();
    }
    
    $(window).on('resize', resize);
    </script>
    
  • 32

    用于嵌入的单层解决方案:以最小尺寸开始并增加到内容大小 . 不需要脚本标签 .

    <iframe src="http://URL_HERE.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>
    
  • 4

    如果您不想使用jQuery,这是一个跨浏览器的解决方案:

    /**
     * Resizes the given iFrame width so it fits its content
     * @param e The iframe to resize
     */
    function resizeIframeWidth(e){
        // Set width of iframe according to its content
        if (e.Document && e.Document.body.scrollWidth) //ie5+ syntax
            e.width = e.contentWindow.document.body.scrollWidth;
        else if (e.contentDocument && e.contentDocument.body.scrollWidth) //ns6+ & opera syntax
            e.width = e.contentDocument.body.scrollWidth + 35;
        else (e.contentDocument && e.contentDocument.body.offsetWidth) //standards compliant syntax – ie8
            e.width = e.contentDocument.body.offsetWidth + 35;
    }
    
  • 3

    我正在使用此代码在页面上加载时自动调整所有iframe(使用类autoHeight)的高度 . 经过测试,适用于IE,FF,Chrome,Safari和Opera .

    function doIframe() {
        var $iframes = $("iframe.autoHeight"); 
        $iframes.each(function() {
            var iframe = this;
            $(iframe).load(function() {
                setHeight(iframe);
            });
        });
    }
    
    function setHeight(e) {
      e.height = e.contentWindow.document.body.scrollHeight + 35;
    }
    
    $(window).load(function() {
        doIframe();
    });
    
  • 0

    在我尝试了地球上的一切之后,这对我来说真的很有用 .

    的index.html

    <style type="text/css">
    html, body{
      width:100%;
      height:100%;
      overflow:hidden;
      margin:0px;   
    }
    </style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
    function autoResize(iframe) {
        $(iframe).height($(iframe).contents().find('html').height());
    }
    </script>
    
    <iframe src="http://iframe.domain.com" width="100%" height="100%" marginheight="0" frameborder="0" border="0" scrolling="auto" onload="autoResize(this);"></iframe>
    
  • 8

    以下是几种方法:

    <body style="margin:0px;padding:0px;overflow:hidden">
        <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe>
    </body>
    

    和另一个替代

    <body style="margin:0px;padding:0px;overflow:hidden">
        <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>
    </body>
    

    用上面的两个替代方案隐藏滚动

    <body style="margin:0px;padding:0px;overflow:hidden">
        <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:150%;width:150%" height="150%" width="150%"></iframe>
    </body>
    

    很高兴第二个代码

    <body style="margin:0px;padding:0px;overflow:hidden">
        <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:150%;width:150%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="150%" width="150%"></iframe>
    </body>
    

    为了隐藏iFrame的滚动条,父级被设置为“overflow:hidden”以隐藏滚动条,并且iFrame的宽度和高度达到150%,这会强制页面外的滚动条,因为身体没有有滚动条可能不会指望iframe超出页面的界限 . 这会全屏隐藏iFrame的滚动条!

    来源:设置iframe auto height

  • -1

    这是一个坚实的证明解决方案

    function resizer(id)
    {
    
    var doc=document.getElementById(id).contentWindow.document;
    var body_ = doc.body, html_ = doc.documentElement;
    
    var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight );
    var width  = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );
    
    document.getElementById(id).style.height=height;
    document.getElementById(id).style.width=width;
    
    }
    

    HTML

    <IFRAME SRC="blah.php" id="iframe1"  onLoad="resizer('iframe1');"></iframe>
    
  • 253

    我略微修改了Garnaph上面的伟大解决方案 . 似乎他的解决方案根据事件之前的大小修改了iframe大小 . 对于我的情况(通过iframe提交电子邮件)我需要在提交后立即更改iframe高度 . 例如,在提交后显示验证错误或“谢谢”消息 .

    我刚刚删除了嵌套的click()函数并将其放入我的iframe html中:

    <script type="text/javascript">
        jQuery(document).ready(function () {
            var frame = $('#IDofiframeInMainWindow', window.parent.document);
            var height = jQuery("#IDofContainerInsideiFrame").height();
            frame.height(height + 15);
        });
    </script>
    

    为我工作,但不确定跨浏览器功能 .

  • 0

    如果您可以控制IFRAME内容和父窗口,那么您需要iFrame Resizer .

    此库可以自动调整相同和跨域iFrame的高度和宽度,以适应其包含的内容 . 它提供了一系列功能来解决使用iFrame的最常见问题,其中包括:

    • 将iFrame的高度和宽度调整为内容大小 .

    • 适用于多个嵌套的iFrame .

    • 跨域iFrame的域身份验证 .

    • 提供一系列页面大小计算方法以支持复杂的CSS布局 .

    • 检测可能导致页面使用MutationObserver调整大小的DOM更改 .

    • 检测可能导致页面调整大小的事件(窗口调整大小,CSS动画和转换,方向更改和鼠标事件) .

    • 通过postMessage在iFrame和主页之间简化消息传递 .

    • 修复了iFrame中的页面链接,并支持iFrame之间的链接和父页面 .

    • 提供自定义大小调整和滚动方法 .

    • 将父位置和视口大小暴露给iFrame .

    • 与ViewerJS一起使用以支持PDF和ODF文档 .

    • 对IE8的后备支持 .

  • 0

    如果有人到达这里:当我从iframe中删除div时我遇到了解决方案的问题 - iframe没有缩短 .

    有一个Jquery插件可以完成这项工作:

    http://www.jqueryscript.net/layout/jQuery-Plugin-For-Auto-Resizing-iFrame-iFrame-Resizer.html

  • 0

    经过一些实验,我想出了另一个解决方案 . 我最初尝试将此问题标记为“最佳答案”的代码,但它无效 . 我的猜测是因为我当时的程序中的iframe是动态生成的 . 这是我使用的代码(它对我有用):

    正在加载的iframe中的Javascript:

    window.onload = function()
        {
            parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
            parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
        };
    

    有必要在高度上添加4个或更多像素以移除滚动条(一些奇怪的错误/ iframe的效果) . 宽度甚至更奇怪,您可以安全地将18px添加到身体的宽度 . 还要确保已应用iframe主体的css(如下所示) .

    html, body {
       margin:0;
       padding:0;
       display:table;
    }
    
    iframe {
       border:0;
       padding:0;
       margin:0;
    }
    

    这是iframe的html:

    <iframe id="fileUploadIframe" src="php/upload/singleUpload.html"></iframe>
    

    以下是我的iframe中的所有代码:

    <!DOCTYPE HTML>
    <html>
    <head>
        <meta charset="utf-8">
        <title>File Upload</title>
        <style type="text/css">
        html, body {
            margin:0;
            padding:0;
            display:table;
        }
        </style>
        <script type="text/javascript">
        window.onload = function()
        {
            parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
            parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
        };
        </script>
    </head>
    <body>
        This is a test.<br>
        testing
    </body>
    </html>
    

    我已经在chrome中进行了测试,并在firefox中进行了一些测试(在windows xp中) . 我还有更多测试要做,所以请告诉我这对你有什么用 .

  • -1

    我发现这个缩放器工作得更好:

    function resizer(id)
    {
    
        var doc = document.getElementById(id).contentWindow.document;
        var body_ = doc.body;
        var html_ = doc.documentElement;
    
        var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight,     html_.scrollHeight, html_.offsetHeight );
        var width  = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );
    
        document.getElementById(id).height = height;
        document.getElementById(id).width = width;
    
    }
    

    请注意,样式对象已删除 .

  • 15

    在jQuery中,这对我来说是最好的选择,真的对我有帮助!!我等着帮助你!

    IFRAME

    <iframe src="" frameborder="0" id="iframe" width="100%"></iframe>
    

    jQuery的

    <script>            
            var valueSize = $( "#iframe" ).offset();
            var totalsize = (valueSize.top * 2) + valueSize.left;
    
            $( "#iframe" ).height(totalsize);            
    
    </script>
    
  • 1

    有可能制作一个像鬼一样的IFrame .

    http://codecopy.wordpress.com/2013/02/22/ghost-iframe-crossdomain-iframe-resize/

    基本上你使用https://developer.mozilla.org/en-US/docs/DOM/window.postMessage中描述的事件系统 parent.postMessage(..)

    这适用于所有现代浏览器!

  • 0

    我就是这样做的(在FF / Chrome中测试):

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
    function autoResize(iframe) {
        $(iframe).height($(iframe).contents().find('html').height());
    }
    </script>
    
    <iframe src="page.html" width="100%" height="100" marginheight="0" frameborder="0" onload="autoResize(this);"></iframe>
    
  • 1

    我知道帖子很旧,但我相信这是另一种方法 . 我刚刚在我的代码上实现了 . 在页面加载和页面调整大小时都可以正常工作:

    var videoHeight;
    var videoWidth;
    var iframeHeight;
    var iframeWidth;
    
    function resizeIframe(){
        videoHeight = $('.video-container').height();//iframe parent div's height
        videoWidth = $('.video-container').width();//iframe parent div's width
    
        iframeHeight = $('.youtubeFrames').height(videoHeight);//iframe's height
        iframeWidth = $('.youtubeFrames').width(videoWidth);//iframe's width
    }
    resizeIframe();
    
    
    $(window).on('resize', function(){
        resizeIframe();
    });
    
  • 1

    Javascript to be placed in header:

    function resizeIframe(obj) {
            obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
          }
    

    Here goes iframe html code:

    <iframe class="spec_iframe" seamless="seamless" frameborder="0" scrolling="no" id="iframe" onload="javascript:resizeIframe(this);" src="somepage.php" style="height: 1726px;"></iframe>
    

    Css stylesheet

    .spec_iframe {
            width: 100%;
            overflow: hidden;
        }
    
  • 1

    对于angularjs指令属性:

    G.directive ( 'previewIframe', function () {
    return {
        restrict : 'A',
        replace : true,
        scope : true,
        link : function ( scope, elem, attrs ) {
            elem.on ( 'load', function ( e ) {
                var currentH = this.contentWindow.document.body.scrollHeight;
                this.style.height = eval( currentH ) + ( (25 / 100)* eval( currentH ) ) + 'px';
            } );
        }
    };
    } );
    

    请注意百分比,我插入它以便您可以计算通常为iframe,文本,广告等进行的缩放,如果没有实现缩放,则只需输入0

  • 0

    如果内容只是一个非常简单的html,最简单的方法是使用javascript删除iframe

    HTML:

    <div class="iframe">
        <iframe src="./mypage.html" frameborder="0" onload="removeIframe(this);"></iframe>
    </div>
    

    JavaScript的:

    function removeIframe(obj)(
        var iframeDocument = obj.contentDocument || obj.contentWindow.document;
        var mycontent = iframeDocument.getElementsByTagName("body")[0].innerHTML;
        obj.remove();
        document.getElementsByClassName("iframe")[0].innerHTML = mycontent;
    }
    
  • 0

    这就是我在上传时或在事情发生变化时的方式 .

    parent.jQuery("#frame").height(document.body.scrollHeight+50);
    
  • 22

    上下文

    我必须在网络扩展的环境中自己做这件事 . 此Web扩展为每个页面注入了一些UI,并且此UI位于 iframe 内 . iframe 内的内容是动态的,所以我必须重新调整 iframe 本身的宽度和高度 .

    我使用 React 但这个概念适用于每个库 .

    我的解决方案(假设您控制页面和iframe)

    iframe 里面,我改变了 body 样式,确实有很大的尺寸 . 这将允许内部元素使用所有必要的空间布局 . 使 widthheight 100%对我不起作用(我猜因为iframe有一个默认的 width = 300pxheight = 150px

    /* something like this */
    body {
      width: 99999px;
      height: 99999px;
    }
    

    然后我在div中注入所有iframe UI并给它一些样式

    #ui-root {
      display: 'inline-block';     
    }
    

    在这个 #ui-root 中渲染我的应用程序后(在React中我在 componentDidMount 内执行此操作)我计算此div的维度并使用 window.postMessage 将它们同步到父页面:

    let elRect = el.getBoundingClientRect()
    window.parent.postMessage({
      type: 'resize-iframe',
      payload: {
        width: elRect.width,
        height: elRect.height
      }
    }, '*')
    

    在父框架中我做这样的事情:

    window.addEventListener('message', (ev) => {
      if(ev.data.type && ev.data.type === 'resize-iframe') {
        iframe.style.width = ev.data.payload.width + 'px'
        iframe.style.height = ev.data.payload.height + 'px'
      }
    }, false)
    
  • 21

    简单:

    var iframe = $("#myframe");
    $(iframe.get(0).contentWindow).on("resize", function(){
        iframe.width(iframe.get(0).contentWindow.document.body.scrollWidth);
        iframe.height(iframe.get(0).contentWindow.document.body.scrollHeight);
    });
    
  • 0

    这仅使用内联CSS:

    <iframe src="http://example.com" style="resize: both;"               
            onload="this.style.height=this.contentDocument.body.scrollHeight +'px'; this.style.width=this.contentDocument.body.scrollWidth +'px';"
            onresize="this.style.height=this.contentDocument.body.scrollHeight +'px'; this.style.width=this.contentDocument.body.scrollWidth +'px';">
    </iframe>
    

相关问题