【问题标题】:to fit iframe to its content height使 iframe 适合其内容高度
【发布时间】:2011-06-11 02:29:13
【问题描述】:
        <script language="JavaScript">
        function autoResize(id){
            alert('check');
            var newheight;
            var newwidth;

            if(document.getElementById){
                newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
                newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
            }
            alert(newheight);
            alert(newwidth);
            document.getElementById(id).height= (newheight) + "px";
            document.getElementById(id).width= (newwidth) + "px";
        }
        </script>

HTML:

            <iframe id="faq_iframe" src="http://www.google.com" width="100%" height="200px" scrolling="no" frameborder="0" marginheight="0" onload="javascript: autoResize('faq_iframe');"></iframe>

问题:我正在使用 iframe 来显示我的页面。我需要使 iframe 适合我的页面高度我该怎么做。

上面的代码我试过了

我通过萤火虫得到了这个错误

Permission denied for <http://localhost> to get property Window.document from <http://www.google.co.in>.
[Break On This Error] newheight=document.getEleme...tWindow.document.body.scrollHeight; 

如何使 iframe 的高度适合 iframe src 中给定的页面高度

【问题讨论】:

    标签: javascript jquery html iframe


    【解决方案1】:

    由于跨域政策,您无法检索 iframe 的高度。为此目的创建服务器端代理。

    【讨论】:

    • 如何创建服务器端代理
    【解决方案2】:

    在你的情况下你不能。

    如果该文档位于另一个域中,则内容位于一个域中的 iframe 无法读取它所注入的文档的任何属性,包括宽度和高度。

    【讨论】:

      【解决方案3】:
      function autoResize(id){
         moz=document.getElementById&&!document.all
         mozHeightOffset=20
         document.getElementById(id).height=window.frames[id].document.body.scrollHeight+(moz?mozHeightOffset:0);
      }
      

      此代码将根据 iframe 的内容调整 iframe 的高度。在 iframe 的 onload 调用这个函数。

      【讨论】:

        【解决方案4】:

        我也一直在为此苦苦挣扎。我最终最终使用了 postMessage (HTML5)。在此处查看示例:cross-domain iframe resizer?

        【讨论】:

          【解决方案5】:

          试试这个,你可以随时改变。本例使用 jQuery。

          $('#iframe').live('mousemove', 函数(事件){

          var theFrame = $(this, parent.document.body);

          this.height($(document.body).height() - 350);
          });

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-10-24
            • 1970-01-01
            • 2016-06-13
            • 1970-01-01
            • 2014-11-08
            • 2022-07-22
            • 1970-01-01
            • 2019-11-24
            相关资源
            最近更新 更多