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


当前回答

简单性:

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

其他回答

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

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

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

到目前为止给出的所有解决方案都只考虑一次调整大小。您提到希望能够在修改内容后调整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内容和父窗口,那么你需要IFRAME调整器。

这个库允许自动调整相同域和跨域iframe的高度和宽度,以适应它们所包含的内容。它提供了一系列功能来解决使用iFrames时最常见的问题,包括:

Height and width resizing of the iFrame to content size. Works with multiple and nested iFrames. Domain authentication for cross domain iFrames. Provides a range of page size calculation methods to support complex CSS layouts. Detects changes to the DOM that can cause the page to resize using MutationObserver. Detects events that can cause the page to resize (Window Resize, CSS Animation and Transition, Orientation Change and Mouse events). Simplified messaging between iFrame and host page via postMessage. Fixes in page links in iFrame and supports links between the iFrame and parent page. Provides custom sizing and scrolling methods. Exposes parent position and viewport size to the iFrame. Works with ViewerJS to support PDF and ODF documents. Fallback support down to IE8.

<iframe src="..." style="border:none; width:100%; height: 100vh;"></iframe>
<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>