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


当前回答

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

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;

}

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

其他回答

这是onload或当事情发生变化时我是怎么做的。

parent.jQuery("#frame").height(document.body.scrollHeight+50);

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

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

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

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

这是一个坚固的解决方案

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>

在jQuery中,这是我最好的选择,这真的帮助了我!!我等待着帮助你!

iframe

<iframe src="" frameborder="0" id="iframe" width="100%"></iframe>

jQuery

<script>            
        var valueSize = $( "#iframe" ).offset();
        var totalsize = (valueSize.top * 2) + valueSize.left;

        $( "#iframe" ).height(totalsize);            

</script>