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


当前回答

<iframe src="hello.html" sandbox="allow-same-origin"
        onload="this.style.height=(this.contentWindow.document.body.scrollHeight+20)+'px';this.style.width=(this.contentWindow.document.body.scrollWidth+20)+'px';">
</iframe>

其他回答

跨浏览器jQuery插件。

cross -bowser, cross - domain library,使用mutationObserver来保持iFrame的大小与内容一致,使用postMessage在iFrame和主机页面之间进行通信。使用或不使用jQuery。

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

简单性:

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

对于angularjs的directive属性:

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如果没有缩放是实现

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

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

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