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


当前回答

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

其他回答

上下文

我不得不在网络扩展的环境中自己做这件事。这个web扩展在每个页面中注入了一些UI,并且这个UI存在于一个iframe中。iframe内部的内容是动态的,所以我必须重新调整iframe本身的宽度和高度。

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

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

在iframe内部,我改变了车身样式,使其具有真正大的尺寸。这将允许内部元素布局使用所有必要的空间。使宽度和高度100%不适合我(我猜是因为iframe有一个默认的宽度= 300px和高度= 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)

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

<iframe src="..." style="border:none; width:100%; height: 100vh;"></iframe>

嵌入式的一行程序解决方案: 从最小大小开始,增加到内容大小。不需要脚本标记。

<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%;" > < / 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>