ChatGPT解决这个技术问题 Extra ChatGPT

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

我需要一种解决方案来自动调整 iframewidthheight 使其几乎不适合其内容。关键是可以在加载 iframe 后更改宽度和高度。我想我需要一个事件操作来处理 iframe 中包含的主体尺寸的变化。

接受的答案不起作用。试试stackoverflow.com/a/31513163/482382
getbootstrap.com/docs/4.0/utilities/embed 经过大量研究后,我恍然大悟,这不是一个独特的问题,我敢打赌 Bootstrap 会处理它。瞧……

C
Cave Johnson
<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/…
G
Guy

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


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

跨浏览器 jQuery plug-in

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


iframe-resizer 库是最强大的解决方案。
G
Garnaph

到目前为止给出的所有解决方案都只考虑一次调整大小。您提到您希望能够在修改内容后调整 iFrame 的大小。为此,您需要在 iFrame 内执行一个函数(一旦内容发生更改,您需要触发一个事件来说明内容已更改)。

我被这个问题困扰了一段时间,因为 iFrame 内的代码似乎仅限于 iFrame 内的 DOM(并且无法编辑 iFrame),并且在 iFrame 外执行的代码被 iFrame 外的 DOM 卡住(并且不能t 拾取来自 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 ()
b
brenjt

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

当来源来自不同域时,是否有任何简单的方法可以做到这一点?
T
Timo Ernst

如果您不想使用 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 你有解决方案吗?
p
petriq

我正在使用此代码在页面上加载所有 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 的内容应该处理这个问题。
A
Adrian P.

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

索引.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
看起来我需要一个非世界的解决方案,因为这不起作用。
M
Mas

这是一个可靠的解决方案

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>

b
bboydflo

语境

我必须在网络扩展的背景下自己做这件事。此网络扩展程序会在每个页面中注入一些 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)

不错的解决方案!谢谢!
u
udackds

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

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


w
www139

经过一些实验,我想出了另一个解决方案。我最初尝试了标记为这个问题的“最佳答案”的代码,但它没有用。我的猜测是因为我当时程序中的 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 中是必需的,所以我出于我的目的将其注释掉。再次感谢。
S
Sergey Ponomarev

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

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

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

适用于多个和嵌套的 iFrame。

跨域 iFrame 的域身份验证。

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

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

检测可能导致页面调整大小的事件(窗口调整大小、CSS 动画和过渡、方向更改和鼠标事件)。

通过 postMessage 简化 iFrame 和主机页面之间的消息传递。

修复 iFrame 中的页面链接并支持 iFrame 和父页面之间的链接。

提供自定义大小和滚动方法。

向 iFrame 公开父位置和视口大小。

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

回退支持到 IE8。


K
Kalaschni

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

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


n
negas

如果您可以使用固定的纵横比并且想要响应式 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有很好的解释。


C
Calciol

可以制作一个“类似幽灵”的 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(..)

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


C
Community

这里有几种方法:

<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%,这迫使滚动条在页面之外,并且由于正文没有t 有滚动条人们可能不会期望 iframe 超出页面的边界。这会以全宽隐藏 iFrame 的滚动条!

来源:设置 iframe auto height


您提供的示例应该使 iframe 完整内容,而不是自动调整 iframe 的高度以适合所有内部内容。它不回答问题。
S
Sarah Sh

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

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

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


c
ctrl-alt-delor

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

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 上对我不起作用 - 内容在底部被部分截断。
K
Kike Gamboa

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

框架

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

H
Henry's Cat

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

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

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

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


x
x19
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%";
}
}

伊夫拉姆风格:

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

这可以支持跨浏览器吗?
L
Latheesan

这就是我的做法(在 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>

如果微软不关心这一点,谁应该关心?
G
Gabriel Ferraz

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

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

A
Alin Razvan

要放置在标题中的 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;
    }

T
Tino Costa 'El Nino'

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


M
MrPHP

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

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

g
gruvw

如果您正在寻找无 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>

O
Ogglas

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

示例错误:

未捕获的 DOMException:阻止具有源“null”的框架访问跨域框架。

相关线程中的答案也是如此:

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


T
Timileyin Oluwayomi

我不知道为什么每个人都只使用 js

css fit-content 可以解决这个问题

iframe{
    height:fit-content;
    width: fit-content;
}