【问题标题】:Adjust width and height of iframe to fit with content in it调整 iframe 的宽度和高度以适应其中的内容
【发布时间】:2010-10-23 14:17:09
【问题描述】:

我需要一种解决方案来自动调整iframewidthheight,使其勉强适应其内容。重点是可以在加载iframe 后更改宽度和高度。我想我需要一个事件操作来处理 iframe 中包含的正文尺寸的变化。

【问题讨论】:

标签: javascript html iframe adjustment


【解决方案1】:
<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>

【讨论】:

  • @StoneHeart:是的,它是跨浏览器。由于没有在 DOM 规范中定义的 contentWindow 属性,该代码不符合标准。在 DOM 规范中存在名为 contentDocument 的属性,但 Internet Explorer 6(和 7?)不支持它。可以改用 contentWindow 属性,它在所有常见的浏览器(Gecko、Opera、Webkit、IE)中实现。
  • if(document.getElementById) 有什么用?
  • 另外不要忘记它不是跨域的。如果域不同,则会出现 Error: Permission denied to access property 'document' 的原因。可以找到解决方案here
  • 条件不仅没有用,而且在极少数情况下,它的目的是保证会导致问题。为什么要检查某个方法是否存在,然后在检查之外使用该方法??
  • 我认为你的意思是DOMContentLoaded,因为DOMContentReady 似乎不是一个东西:developer.mozilla.org/en-US/…
【解决方案2】:

嵌入的单线解决方案: 从最小尺寸开始并增加内容大小。不需要脚本标签。

&lt;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;"&gt;&lt;/iframe&gt;

【讨论】:

  • 运行代码 sn-p 不适用于 Safari 9.1.1 可能包含 SO 问题?
  • 不是跨域的。也许服务器需要在框架页面中添加一些标题?
  • 此处提及scrollHeight/scrollWidth 的所有答案都应稍作调整以考虑正文边距。浏览器为文档的正文元素应用默认的非零边距(它也适用于加载到框架中的内容)。我找到的工作解决方案是添加这个:parseInt(window.getComputedStyle(this.contentDocument.body).margin.
  • @Stan 文档中可能有一些元素的边距大于正文的边距,这在您的解决方案中也没有考虑。
  • @Stan 使用body.parentElement.scrollHeight 而不是body.scrollHeight(宽度相同),它将包括文档边距和其他内容。如果您使用 body,则最终会排除顶级 html 元素的边距/填充。
【解决方案3】:

跨浏览器jQuery plug-in.

Cross-bowser,跨域 library 使用 mutationObserver 保持 iFrame 大小适合内容,postMessage 在 iF​​rame 和主机页面之间进行通信。使用或不使用 jQuery。

【讨论】:

  • iframe-resizer 库是最强大的解决方案。
【解决方案4】:

到目前为止给出的所有解决方案都只考虑了一次调整大小。您提到您希望能够在修改内容后调整 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>

【讨论】:

  • 完整的代码是什么?我假设脚本进入 iframe html?
  • 这是完整的代码,是的,它在 iFrame 的 HTML 中运行。 “window.parent.document”部分指定 jQuery 选择器应该使用父文档的 DOM,而不是您所在的文档(在 iFrame 内)。
  • 如果父文档和 iframe 中的文档都来自同一域,这将非常有效。如果它们不是(或者,在 chrome 中,if they're both local files),那么浏览器的“同源”安全策略就会启动,它会阻止 iframe 内容修改父文档。
  • 对于任何试图跨域工作的人,请查看window.postMessage (IE8+) 并注意您需要在主机(父)和源(在 iframe 中)文件。 jQuery postmessage plugin 可能会有所帮助。由于您需要主机和源上的脚本,因此让主机使用 JSON-P 通过 AJAX 加载内容可能更容易。
  • 如何自动触发事件而不是jQuery("#IDofControlFiringResizeEvent").click(function ()
【解决方案5】:

如果 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>

【讨论】:

  • 当来源来自不同域时,有什么简单的方法可以做到这一点吗?
【解决方案6】:

如果你不想使用 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;
}

【讨论】:

  • 这很奇怪。对我来说,它计算出非常奇怪的 iframe 宽度。内容宽度为 750,计算为 300。您知道为什么吗?
  • 我玩过这段代码(添加了高度选项)。如果我将 iFrame 高度设置为 100%,它会将其限制为大约 200 像素。如果我将 iFrame 高度设置为 600 像素,它会坚持下去。 @RobertJagoda 你有解决办法吗?
【解决方案7】:

我正在使用此代码在页面加载时自动调整所有 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();
});

【讨论】:

  • 您要添加的魔法 35 是什么?您针对哪个浏览器和操作系统进行了测量?
  • 现在我真的不知道为什么我添加了 35 个像素。但我可以肯定地告诉你,我在 FF、IE (7, 8, 9) 和 Chrome 上测试了它,并且运行良好。
  • 我认为 35 只是滚动条的厚度
  • 我不得不稍微调整一下才能让它工作 - 称为 setHeight(iframe);直接(移除了它周围的 $(iframe).load() 包装器。
  • 添加的魔法 35 像素是为了考虑 iframe 填充。我要补充一点,iframe 应该不包含填充 iframe 的内容应该解决这个问题。
【解决方案8】:

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

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>

【讨论】:

  • 它说:Uncaught TypeError: $ is not a function at autoResize ((index):200) at HTMLIFrameElement.onload ((index):204)
  • @Michael Rogers 与 $ 冲突,或者您忘记包含 jQuery.js 文件。使用通用函数stackoverflow.com/questions/6109847/… 或将 $ 替换为 jQuery
  • 看来我需要一个外星解决方案,因为这行不通。
【解决方案9】:

这是一个可靠的解决方案

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>

【讨论】:

    【解决方案10】:

    我在上面稍微修改了 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>
    

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

    【讨论】:

      【解决方案11】:

      经过一些实验,我想出了另一个解决方案。我最初尝试了标记为这个问题的“最佳答案”的代码,但它没有用。我的猜测是因为我当时程序中的 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 添加到 body 的宽度。还要确保您已应用 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 中)。我还有更多的测试要做,所以请告诉我这对你有什么作用。

      【讨论】:

      • 谢谢你,根据我的测试,这在移动浏览器中的效果非常好,这就是我在调整 iframe 大小时遇到​​的问题!
      • 很高兴你喜欢它 :-) 我发现 iframe 在大多数情况下比 Ajax 效率更高,并且提供更好的浏览器支持。
      • 谢谢!!!主要是因为你是唯一一个在不假设人们知道的情况下指定将代码放在哪里的人。这个简单的解决方案非常适合我(Firefox、Chrome、Edge),用于在我的 Wordpress 网站的同一域中构建动态内容。我有一个表单选择,它将输出各种长度的动态内容。 iFrame 调整得很漂亮。我确实必须调整 .clientHeight+5+'px';和clientWidth+18+'px';是更多的像素。而且我不确定为什么 display:table;在 CSS 中是必需的,所以我出于我的目的将其注释掉。再次感谢。
      【解决方案12】:

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

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

      • 将 iFrame 的高度和宽度调整为内容大小。
      • 适用于多个嵌套 iFrame。
      • 跨域 iFrame 的域身份验证。
      • 提供一系列页面大小计算方法来支持复杂的 CSS 布局。
      • 使用 MutationObserver 检测可能导致页面调整大小的 DOM 更改。
      • 检测可导致页面调整大小的事件(窗口调整大小、CSS 动画和过渡、方向更改和鼠标事件)。
      • 通过 postMessage 简化 iFrame 和主机页面之间的消息传递。
      • 修复了 iFrame 中的页面链接并支持 iFrame 和父页面之间的链接。
      • 提供自定义大小和滚动方法。
      • 向 iFrame 公开父位置和视口大小。
      • 与 ViewerJS 配合使用以支持 PDF 和 ODF 文档。
      • 回退支持到 IE8。

      【讨论】:

        【解决方案13】:

        上下文

        我必须自己在网络扩展的上下文中执行此操作。这个网络扩展在每个页面中注入了一些 UI,这个 UI 存在于 iframe 中。 iframe 内的内容是动态的,所以我不得不重新调整 iframe 本身的宽度和高度。

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

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

        iframe 内部,我将body 样式更改为具有非常大的尺寸。这将允许内部元素使用所有必要的空间进行布局。使widthheight 100% 对我不起作用(我猜是因为iframe 有默认的width = 300pxheight = 150px

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

        然后我将所有 iframe UI 注入到一个 div 中,并给它一些样式

        #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)
        

        【讨论】:

        • 不错的解决方案!谢谢!
        【解决方案14】:

        使用上述方法都无法正常工作。

        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

        【讨论】:

          【解决方案15】:

          可以制作一个“类似幽灵”的 IFrame,就像它不存在一样。

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

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

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

          【讨论】:

            【解决方案16】:

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

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

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

            【讨论】:

              【解决方案17】:

              我发现这个调整器效果更好:

              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;
              
              }
              

              注意样式对象已被移除。

              【讨论】:

              • 在 Chrome/Win10 上对我不起作用 - 内容在底部被部分截断。
              【解决方案18】:

              在 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>
              

              【讨论】:

                【解决方案19】:

                显然有很多场景,但是,我的文档和 iframe 具有相同的域,并且我能够将其附加到 iframe 内容的末尾:

                var parentContainer = parent.document.querySelector("iframe[src*=\"" + window.location.pathname + "\"]");
                parentContainer.style.height = document.body.scrollHeight + 50 + 'px';
                

                这会“找到”父容器,然后将长度添加到 50 像素的软糖因子上以移除滚动条。

                没有什么可以“观察”文档高度的变化,我的用例不需要这个。在我的回答中,我确实带来了一种引用父容器的方法,而不使用烘焙到父/iframe 内容中的 id。

                【讨论】:

                  【解决方案20】:

                  如果您可以接受固定纵横比,并且想要响应式 iframe,那么此代码将对您有用。这只是 CSS 规则。

                  .iframe-container {
                    overflow: hidden;
                    /* Calculated from the aspect ration of the content (in case of 16:9 it is 9/16= 
                    0.5625) */
                    padding-top: 56.25%;
                    position: relative;
                  }
                  .iframe-container iframe {
                    border: 0;
                    height: 100%;
                    left: 0;
                    position: absolute;
                    top: 0;
                    width: 100%;
                  }
                  

                  iframe 必须有一个 div 作为容器。

                  <div class="iframe-container">
                     <iframe src="http://example.org"></iframe>
                  </div>
                  

                  源码基于这个siteBen Marshall有很好的解释。

                  【讨论】:

                    【解决方案21】:
                    function resizeIFrameToFitContent(frame) {
                    if (frame == null) {
                        return true;
                    }
                    
                    var docEl = null;
                    var isFirefox = navigator.userAgent.search("Firefox") >= 0;
                    
                    if (isFirefox && frame.contentDocument != null) {
                        docEl = frame.contentDocument.documentElement;
                    } else if (frame.contentWindow != null) {
                        docEl = frame.contentWindow.document.body;
                    }
                    
                    if (docEl == null) {
                        return;
                    }
                    
                    var maxWidth = docEl.scrollWidth;
                    var maxHeight = (isFirefox ? (docEl.offsetHeight + 15) : (docEl.scrollHeight + 45));
                    
                    frame.width = maxWidth;
                    frame.height = maxHeight;
                    frame.style.width = frame.width + "px";
                    frame.style.height = frame.height + "px";
                    if (maxHeight > 20) {
                        frame.height = maxHeight;
                        frame.style.height = frame.height + "px";
                    } else {
                        frame.style.height = "100%";
                    }
                    
                    if (maxWidth > 0) {
                        frame.width = maxWidth;
                        frame.style.width = frame.width + "px";
                    } else {
                        frame.style.width = "100%";
                    }
                    }
                    

                    ifra 样式:

                    .myIFrameStyle {
                       float: left;
                       clear: both;
                       width: 100%;
                       height: 200px;
                       padding: 5px;
                       margin: 0px;
                       border: 1px solid gray;
                       overflow: hidden;
                    }
                    

                    iframe 标签:

                    <iframe id="myIframe" src="" class="myIFrameStyle"> </iframe>
                    

                    脚本标签:

                    <script type="text/javascript">
                       $(document).ready(function () {
                          $('myIFrame').load(function () {
                             resizeIFrameToFitContent(this);
                          });
                        });
                    </script>
                    

                    【讨论】:

                    • 这个可以支持跨浏览器吗?
                    【解决方案22】:

                    我会这样做(在 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>
                    

                    【讨论】:

                    • 如果微软不关心这个,谁来关心?
                    【解决方案23】:

                    这里有几种方法:

                    <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>
                    

                    如上所示,使用 2 个选项隐藏滚动

                    <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%,这会强制滚动条在页面外,因为body 没有滚动条,人们可能不会期望 iframe 超出页面的边界。这会隐藏 iFrame 的滚动条全宽!

                    来源:设置iframe auto height

                    【讨论】:

                    • 您提供的示例应该使 iframe 完整内容,而不是自动调整 iframe 的高度以适应所有内部内容。它不回答问题。
                    【解决方案24】:

                    我知道这篇文章已经过时了,但我相信这是另一种方法。我刚刚在我的代码上实现了。在页面加载和页面调整大小时完美运行:

                    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();
                    });
                    

                    【讨论】:

                      【解决方案25】:

                      要放在标题中的Javascript:

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

                      这里是 iframe html 代码:

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

                      Css 样式表

                      >

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

                      【讨论】:

                        【解决方案26】:

                        对于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

                        【讨论】:

                          【解决方案27】:

                          这就是我在加载或事情发生变化时的方式。

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

                          【讨论】:

                            【解决方案28】:

                            如果你正在寻找一个没有 jQuery 跨域的解决方案,你可能想看看我的想法:

                            <main id="container"></main>
                            <script>
                              fetch('https://example.com').then(response => {
                                return response.text();
                              }).then(data => {
                                const iframeContainer = window.document.getElementById('container');
                                const iframe = document.createElement('iframe');
                                iframe.frameBorder = 'none';
                                iframe.width = '100%';
                                iframe.addEventListener("load", function() {
                                  iframe.height = iframe.contentWindow.document.body.scrollHeight;
                                })
                                const finalHtml = data;
                                const blob = new Blob([finalHtml], {type: 'text/html'});
                                iframe.src = window.URL.createObjectURL(blob);
                                iframeContainer.appendChild(iframe);
                              })
                            </script>
                            

                            【讨论】:

                              【解决方案29】:

                              我在这里阅读了很多答案,但几乎每个人都给出了某种跨域框架块。

                              示例错误:

                              Uncaught DOMException: Blocked a frame with origin "null" from 访问跨域框架。

                              相关帖子中的答案也是如此:

                              Make iframe automatically adjust height according to the contents without using scrollbar?

                              我也不想使用像 iFrame Resizer 这样的第三方库或类似的库。

                              @bboydflo 的答案很接近,但我缺少一个完整的例子。 https://stackoverflow.com/a/52204841/3850405

                              我将width="100%" 用于iframe,但代码也可以修改为使用宽度。

                              这就是我解决为iframe 设置自定义高度的方法:

                              内嵌iframe:

                              <!DOCTYPE html>
                              <html lang="en">
                              <head>
                                  <meta charset="utf-8" />
                                  <meta name="description"
                                        content="Web site" />
                                  <title>Test with embedded iframe</title>
                              </head>
                              <body>
                                  <noscript>You need to enable JavaScript to run this app.</noscript>
                                  <div id="root"></div>
                                  <iframe id="ifrm" src="https://localhost:44335/package/details?key=123" width="100%"></iframe>
                                  <script type="text/javascript">
                                      window.addEventListener('message', receiveMessage, false);
                              
                                      function receiveMessage(evt) {
                                          console.log("Got message: " + JSON.stringify(evt.data) + " from origin: " + evt.origin);
                                          // Do we trust the sender of this message?
                                          if (evt.origin !== "https://localhost:44335") {
                                              return;
                                          }
                              
                                          if (evt.data.type === "frame-resized") {
                                              document.getElementById("ifrm").style.height = evt.data.value + "px";
                                          }
                                      }
                                  </script>
                              </body>
                              </html>
                              

                              iframe source,来自Create React App 的示例,但仅使用了HTMLJS

                              <!DOCTYPE html>
                              <html lang="en">
                              <head>
                                  <meta charset="utf-8" />
                                  <meta name="description"
                                        content="Web site created using create-react-app" />
                                  <title>React App</title>
                              </head>
                              <body>
                                  <noscript>You need to enable JavaScript to run this app.</noscript>
                                  <div id="root"></div>
                                  <script type="text/javascript">
                                      //Don't run unless in an iframe
                                      if (self !== top) {
                                          var rootHeight;
                                          setInterval(function () {
                                              var rootElement = document.getElementById("root");
                                              if (rootElement) {
                                                  var currentRootHeight = rootElement.offsetHeight;
                                                  //Only send values if height has changed since last time
                                                  if (rootHeight !== currentRootHeight) {
                                                      //postMessage to set iframe height
                                                      window.parent.postMessage({ "type": "frame-resized", "value": currentRootHeight }, '*');
                                                      rootHeight = currentRootHeight;
                                                  }
                                              }
                                          }
                                              , 1000);
                                      }
                                  </script>
                              </body>
                              </html>
                              

                              setInterval 的代码当然可以修改,但它非常适用于动态内容。 setInterval 仅在内容嵌入 iframe 时激活,postMessage 仅在高度更改时发送消息。

                              您可以在此处阅读有关 Window.postMessage() 的更多信息,但该描述非常符合我们想要实现的目标:

                              window.postMessage() 方法可以安全地启用跨域 Window 对象之间的通信;例如,在一个页面和一个 它产生的弹出窗口,或在页面和嵌入的 iframe 之间 在里面。

                              通常情况下,不同页面上的脚本是允许相互访问的 当且仅当它们源自的页面共享相同的协议, 端口号和主机(也称为“同源策略”)。 window.postMessage() 提供了一种受控机制来安全地 绕过这个限制(如果使用得当的话)。

                              https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

                              如果您想要 iframe 的 100% 宽度和高度,我会这样做:

                              <!DOCTYPE html>
                              <html lang="en">
                              <head>
                                  <meta charset="utf-8" />
                                  <meta name="description"
                                        content="Web site" />
                                  <style>
                                      body {
                                          margin: 0; /* Reset default margin */
                                      }
                              
                                      iframe {
                                          display: block; /* iframes are inline by default */
                                          background: #000;
                                          border: none; /* Reset default border */
                                          height: 100vh; /* Viewport-relative units */
                                          width: 100vw;
                                      }
                                  </style>
                                  <title>Test with embedded iframe</title>
                              </head>
                              <body>
                                  <iframe src="https://localhost:44335/package/details?key=123"></iframe>
                              </body>
                              </html>
                              

                              来源:

                              https://stackoverflow.com/a/27853830/3850405

                              【讨论】:

                                【解决方案30】:

                                简单:

                                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);
                                });
                                

                                【讨论】:

                                  猜你喜欢
                                  • 2016-06-13
                                  • 2014-10-24
                                  • 1970-01-01
                                  • 2015-04-07
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多