【问题标题】:How to change height of iframe based on dynamic conent within the iframe?如何根据 iframe 中的动态内容更改 iframe 的高度?
【发布时间】:2012-01-06 22:43:22
【问题描述】:

我有一个包含动态内容的 iframe。如果回答特定问题,则会显示附加信息(隐藏的 div 变为可见)。我想扩大 iframe 的高度。我知道这个问题已经在这里被问过很多次了,但似乎它通常是在 iframe 中的不同页面被加载时,而不是在 iframe 中动态更改内容时。

这是我尝试使用 jsFiddle 整理的示例:

iframe:http://jsfiddle.net/B4AKc/2/

页面:http://jsfiddle.net/PmBrd/

有什么想法吗?

【问题讨论】:

  • 这仍然是一个棘手的问题。这是关于 SO 的最佳答案:stackoverflow.com/questions/153152/…
  • iframe 中的内容是否与包含 iframe 的页面在同一个域中?
  • 同一个域?该死的,我以为我得到了一个快速、简单的答案!

标签: jquery iframe dynamic height


【解决方案1】:

这对你有用吗?

http://jsfiddle.net/PmBrd/1/

代码:

var iframe = document.getElementById("ifr").contentWindow;

iframe.$(".toggle_div").bind("change", function () {
    $("#ifr").css({
        height: iframe.$("body").outerHeight()
    });
});

由于您提到它们在同一个域中,因此只需对您的真实应用执行类似操作即可。

【讨论】:

    【解决方案2】:

    看看 jQuery postMessage 插件。它允许您将信息从子框架传递给父框架。您可以更改子框架内的代码,以便在内容更改时将内容高度发布给父级,然后父级可以使用它来相应地调整 iframe 的大小。

    两个页面必须在同一个域中才能工作。

    我希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      Esailija 的回答效果很好,但这更好 imo。

      $('#ifr').contents($(".toggle_div")).bind("change", function () {
          $("#ifr").height($("#ifr").contents().find("html").height());
      });
      

      【讨论】:

        【解决方案4】:

        检查这个。 您可以使用 javascript 本身获取 iframe 大小。
        使用 setInterval,每次检查窗口高度。

        < iframe src='<YOUR_URL>' frameborder='0' scrolling='no' id='frame_id' style='overflow:hidden; width:984px;' >
        </iframe>
        
        <script language="javascript" type="text/javascript">
        setInterval(function(){
            document.getElementById("frame_id").style.height = document.getElementById("frmid").contentWindow.document.body.scrollHeight + 'px';
        },1000)
        </script>
        

        Check this

        【讨论】:

          【解决方案5】:

          可能有点晚了,因为所有其他答案都来自 2011 年 :-) 但是...... 这是我的解决方案。在实际 FF、Chrome 和 Safari 5.0 中测试

          $(document).ready(function(){
              $("iframe").load( function () {
                  var c = (this.contentWindow || this.contentDocument);
                  if (c.document) d = c.document;
                  var ih = $(d).outerHeight();
                  var iw = $(d).outerWidth();
                  $(this).css({
                      height: ih,
                      width: iw
                  });
              });
          });
          

          希望这对任何人都有帮助。

          【讨论】:

            猜你喜欢
            • 2012-09-28
            • 2013-03-06
            • 2016-06-17
            • 2012-05-21
            • 2011-11-17
            • 2012-07-29
            • 2022-06-21
            • 2011-10-24
            • 2013-08-02
            相关资源
            最近更新 更多