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


当前回答

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

其他回答

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

可以创建一个“幽灵般的”IFrame,就像它不存在一样。

参见http://codecopy.wordpress.com/2013/02/22/ghost-iframe-crossdomain-iframe-resize/

中描述的事件系统parent.postMessage(..) https://developer.mozilla.org/en-US/docs/DOM/window.postMessage

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

上下文

我不得不在网络扩展的环境中自己做这件事。这个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)

我发现这个调整器工作得更好:

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;

}

注意,样式对象被删除了。