我需要一个自动调整iframe的宽度和高度的解决方案,以勉强适应其内容。关键是宽度和高度可以在iframe加载后改变。我想我需要一个事件动作来处理iframe中包含的主体尺寸的变化。


当前回答

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

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

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

其他回答

以防有人说到这里 当我从iframe中删除div时,我有一个解决方案的问题- iframe没有变短。

有一个Jquery插件,做的工作:

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

我使用这段代码自动调整所有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();
});

使用bootstrap的嵌入响应类,它最初是为youtube视频,但你可以调整它的高度。

如果你不能使用javascript,我建议使用引导和玩周围的嵌入响应-***类的html。我能够通过添加填充底部作为百分比来实现同样的效果,从而进一步相应地调整它。

<span class="iframe embed-responsive embed-responsive-16by9" style="display:block; padding-bottom: 10%;">
<iframe class="embed-responsive-item" width="100%" scrolling="no" src="example.com" frameBorder="0" ></iframe>
</span>

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

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

对我来说有用,但不确定跨浏览器功能。