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


当前回答

显然有很多场景,但是,我有相同的域文档和iframe,我能够将此附加到我的iframe内容的末尾:

var parentContainer = parent.document.querySelector("iframe[src*=\"" + window.location.pathname + "\"]");
parentContainer.style.height = document.body.scrollHeight + 50 + 'px';

这将“找到”父容器,然后设置长度加上50像素的模糊因子以删除滚动条。

这里没有任何东西可以“观察”文档高度的变化,这在我的用例中是不需要的。在我的回答中,我带来了一种引用父容器而不使用父/iframe内容中的id的方法。

其他回答

这是一个坚固的解决方案

function resizer(id)
{

var doc=document.getElementById(id).contentWindow.document;
var body_ = doc.body, 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).style.height=height;
document.getElementById(id).style.width=width;

}

html

<IFRAME SRC="blah.php" id="iframe1"  onLoad="resizer('iframe1');"></iframe>

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

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

在我试遍了世界上所有的方法之后,这个方法真的很适合我。

index . html

<style type="text/css">
html, body{
  width:100%;
  height:100%;
  overflow:hidden;
  margin:0px;   
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
    $(iframe).height($(iframe).contents().find('html').height());
}
</script>

<iframe src="http://iframe.domain.com" width="100%" height="100%" marginheight="0" frameborder="0" border="0" scrolling="auto" onload="autoResize(this);"></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 >

这是我怎么做的(在FF/Chrome测试):

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
    $(iframe).height($(iframe).contents().find('html').height());
}
</script>

<iframe src="page.html" width="100%" height="100" marginheight="0" frameborder="0" onload="autoResize(this);"></iframe>