如何使用动态内容调整iframe的大小?

时间:2011-01-03 17:01:43

标签: iframe resize dynamic-content

我正在使用注入其中的一些内容填充iframe,但我无法正确调整大小。我尝试了各种方法,但这里是最新的代码。

使用基于html的邮件消息填充iframe后,似乎没有注册滚动高度。

    <iframe scrolling="no" width="100%" onload="javascript:(LoadIFrame(this));" >
HTML content goes here.  Make sure it's long enough to need to scroll before testing.
</iframe>

<script type="text/javascript">
    function LoadIFrame(iframe) {
        $("iframe").each(function() {
            $(this).load(function() {
                var doc = this.document;
                if (this.contentDocument) {
                    doc = this.contentDocument;
                } else if (this.contentWindow) {
                    doc = this.contentWindow.document;
                } else if (this.document) {
                    doc = this.document;
                }
                this.height = (doc.body.scrollHeight + 50) + 'px';
                this.onload = '';
            });

            txt = $(this).text();
            var doc = this.document;
            if (this.contentDocument) {
                doc = this.contentDocument;
            } else if (this.contentWindow) {
                doc = this.contentWindow.document;
            } else if (this.document) {
                doc = this.document;
            }
            doc.open();
            doc.writeln(txt);
            doc.close();
        });
    }
</script>

2 个答案:

答案 0 :(得分:0)

不确定您遇到问题的地方......

你应该能够快速调整它的大小

***已更新

theframe.height = document.frames ['sizedframe']。document.body.scrollHeight +'px'; }

***您可能遇到了安全问题: Set iframe to height of content for remote content

对于来自同一域/本地的内容-it将工作...(已验证)..如果您尝试加载远程页面,它将无法正常工作...

本作品

<iframe id="sizedframe" style="width:100%" onload="sizeframe(this);" src="demo.htm"></iframe>

这不是(除非从stackoverflow上的页面调用它)

<iframe id="sizedframe" style="width:100%" onload="sizeframe(this);" src="http://www.stackoverflow.com"></iframe>

答案 1 :(得分:0)

添加另一个答案因为它更容易......

结帐:http://thomas.bindzus.me/2007/12/24/adding-dynamic-contents-to-iframes/ 我刚从帖子的末尾抓住了他的IFrame.js来创建动态框架......

所以试试他的例子,看看它没有做到......

然后换掉HTML ...

<html>
   <head>
      <title>Adding Dynamic Contents to IFrames</title>

      <script type="text/javascript" src="IFrame.js"></script>
      <script type="text/javascript">
         function onPageLoad()
         {
            var canvas = document.getElementById("canvas");
            var iframe = new IFrame(canvas);

            var div = iframe.doc.createElement("div");
            div.innerHTML = "Hello IFrame!";
            iframe.doc.body.appendChild(div);

            frameheight = iframe.document.body.scrollHeight;
            iframe.width = '100%';
            iframe.height = frameheight + 'px';
         }


      </script>
   </head>

   <body onload="onPageLoad();">
      <div id="canvas" style="border: solid 1px #000000; height: 500px; width: 500px;"></div>
   </body>
</html>

**在“你好框架”中我只是一堆垃圾文本导致它调整大小...

只有垮台是画布设置的最大高度......但是可以通过调整'画布'高度来解决这个问题......

相关问题