首页 文章

将iframe高度设置为内部内容的高度(在同一域上)

提问于
浏览
1

我的页面中嵌入了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的大小,但只调整了其原始高度的10px - 如果内容长于此值,它仍然是隐藏的 .

也许我需要iframe体内的onload事件?

3 回答

  • 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>
    
  • 0

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

    您可以使用以下代码段将iframe设置为内容高度 .

    JS:

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

    HTML:

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

    请注意,仅当iframe网址位于包含iframe本身的网页的 exact same domain 时,此功能才有效 .

  • -1

    没有jquery:

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

相关问题