【问题标题】:Set iframe height to that of internal content (on same domain)将 iframe 高度设置为内部内容的高度(在同一域上)
【发布时间】:2010-10-01 19:51:25
【问题描述】:

我的页面中嵌入了一个 iframe - 它只是我页面的一部分,而不是全部。我正在动态重新加载 iframe,并希望它根据其中内容的高度调整大小。

内容在同一个域中,所以(希望如此?)不需要像Resizing an iframe based on content 中给出的那样复杂的解决方案。

这是我用来调整它大小的代码,但它不起作用。框架重新加载正常,但高度始终保持不变。谁能给点建议?

我也尝试了How to autosize an iframe 中的顶级解决方案,但没有任何运气。

我认为这可能是因为 iframe 内的页面需要一段时间才能加载,所以在设置高度时它还没有完成加载。也许吧。

<iframe frameborder=0 border=0 src="" width="100%" height="400px" name="commentframe" id="commentframe"></iframe>
function reload_frame(uid) {
    document.getElementById('commentframe').src = "comments.html?" + uid;
    document.getElementById('commentframe').height = document.getElementById('commentframe').contentWindow.document.body.scrollHeight + "px";
}

更新:

尝试,没有运气:

<iframe frameborder=0 border=0 src="" width="100%" height="400px" name="commentframe" id="commentframe" onload="reload_frame()"></iframe>
function reload_frame() {
        var commentframe = document.getElementById('commentframe');
        commentframe.style.height = (commentframe.scrollHeight + 10).toString() + "px";
}

它确实会调整 iframe 的大小,但只会调整到其原始高度的 +10 像素 - 如果内容比这长,它仍然是隐藏的。

也许我需要在 iframe 本身的主体内添加一个 onload 事件?

【问题讨论】:

  • commentframe.style.height 更改为commentframe.height(在update 部分中)。

标签: javascript html iframe


【解决方案1】:
<script type="text/javascript">
    function ajustHeight() {
        $("#myIframe").parent()[0].style.height = ($("#myIframe")[0].scrollHeight + 150).toString() + "px";
    }
</script>
<iframe id="myIframe" src="mypage.html" width="100%" height="100%" onload="ajustHeight()"></iframe>

【讨论】:

  • 为什么+150?我们期望在这里发生什么?
  • 谢谢!有没有办法在没有 jquery 的情况下用普通的 Javascript 编写它?我只是想翻译...
  • parent() 调用是做什么的?我的 iframe 不在包含的 div 内(请注意,它不是页面上唯一的东西......),那么它的高度到底设置了什么?
  • 不用担心。只需要弄清楚如何将它用于没有父级的 iframe?
  • 这对我有用: $('iframe[name=reporting_frame]').load(function() { $(this).height( $(this)[0].contentWindow. document.body.scrollHeight + 24); });
【解决方案2】:

在现代浏览器和许多文档类型中,scrollHeight 将返回浏览器计算的 iframe 高度而不是内容高度,因此在大多数情况下,上述 sn-ps 将不起作用。

您可以使用以下 sn-p 将 iframe 设置为内容高度。

JS:

$('#ifm').load(function() {
  $(this).height( $(this)[0].contentWindow.document.body.scrollHeight + 24);
});

HTML:

<iframe id="ifm  src="..."></iframe>

请注意,只有当 iframe URL 位于包含 iframe 本身的页面的完全相同的域上时,这才有效。

【讨论】:

    【解决方案3】:

    没有 jquery:

    <script type="text/javascript">
        window.onload = function() {
            var iframe = document.getElementById("blogFrame");
            iframe.parentNode.style.height = iframe.scrollHeight + "px";
        }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2010-10-02
      • 2016-04-03
      • 2014-11-06
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 2013-11-22
      • 2014-08-02
      • 1970-01-01
      相关资源
      最近更新 更多