简体   繁体   English

通过JavaScript调整iFrame内容的大小

[英]Resize iFrame Content Via JavaScript

I am wondering if theres some way to make it so that if there is a bunch of content in an iFrame it will just resize the document essentially so it fits. 我想知道是否有某种方法可以使它,如果iFrame中有一堆内容,它将实质上调整文档的大小以使其适合。 Making all the content inside the iFrame smaller. 缩小iFrame内部的所有内容。 To clarify I want to resize the content, not the iFrame's size itself. 为了明确起见,我想调整内容的大小,而不是iFrame的大小。

Any ideas how I would do this? 有什么想法我会怎么做吗?

I have tried out some stuff but so far no luck. 我已经尝试了一些东西,但到目前为止还没有运气。

Script: 脚本:

<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:

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

By the way the reason there is no src set for the iFrame is because I have it in JavaScript so when you click aa button it will edit the html of the iFrame via jQuery. 顺便说一下,没有为iFrame设置src的原因是因为我在JavaScript中有它,所以当您单击一个按钮时,它将通过jQuery编辑iFrame的html。

You can use load event to resize iframe 您可以使用加载事件来调整iframe的大小

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

You should be able to achieve this using jQuery .contents() - 您应该可以使用jQuery .contents()实现此目的-

assuming id is the id of the element you wish to change within the iframe: 假设id是您希望在iframe中更改的元素的id:

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

See http://forum.jquery.com/topic/changing-elements-in-an-iframe 参见http://forum.jquery.com/topic/changing-elements-in-an-iframe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM