【问题标题】:Resize iFrame Content Via JavaScript通过 JavaScript 调整 iFrame 内容的大小
【发布时间】:2013-12-26 08:20:23
【问题描述】:

我想知道是否有某种方法可以做到这一点,如果 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。

【问题讨论】:

    标签: javascript jquery html iframe


    【解决方案1】:

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

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

    【讨论】:

    • 查看我对 aruuu 回答的评论 :)
    【解决方案2】:

    您应该能够使用 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

    【讨论】:

    • 当我点击 iFrame 时,它​​仍然有滚动条。
    • iframe 中的内容是什么? id 是 iframe 本身的 id,还是要在 iframe 中更改的元素的 id?
    • 嗯,实际上并没有 iFrame 的来源,这就是问题所在。正如我所说,iFrame 中的内容实际上只是使用 .contents().html('test') 设置的。它实际上不是一个来源。这就是为什么我不相信我可以使用加载功能。
    • 你为什么使用 .contents.html('test') 而不是 $('#iframehtml').src = 'test'?
    • 这根本没有多大意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2010-09-14
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    相关资源
    最近更新 更多