通过JavaScript调整iFrame内容的大小

时间:2013-11-05 00:18:15

标签: javascript jquery html iframe

我想知道是否有某种方式可以使它如果iFrame中有一堆内容,它只会调整文档的大小,以便它适合。使iFrame内的所有内容变小。为了澄清我想要调整内容的大小,而不是iFrame的大小本身。

我会怎么做?

我尝试了一些东西,但到目前为止没有运气。

脚本:

<script type="text/javascript">
function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}
</script>

的iFrame:

<iframe id="iframehtml" style="width:100%;height:100%;" onLoad="autoResize('iframe1');"></iframe>

顺便说一下,没有为iFrame设置src的原因是因为我在JavaScript中有它,所以当你点击一个按钮时它会通过jQuery编辑iFrame的html。

2 个答案:

答案 0 :(得分:1)

您可以使用加载事件来调整iframe的大小

var iframe = document.getElementByID('your-iframe');
iframe.addEventListener('load', function() {
  iframe.style.height = iframe.contentWindow.document.body.offsetHeight + 'px';
})

答案 1 :(得分:0)

您应该能够使用jQuery .contents() -

来实现这一目标

假设 id 是您希望在iframe中更改的元素的ID:

var frame = $('#iframehtml')
frame.contents().find(id).width = (newheight) + "px";

请参阅http://forum.jquery.com/topic/changing-elements-in-an-iframe

相关问题