【问题标题】:Get iframe content height in Google Chrome在 Google Chrome 中获取 iframe 内容高度
【发布时间】:2015-05-04 16:38:26
【问题描述】:

谁能帮我把这段代码在谷歌浏览器上运行? 它在 IE 上完美运行。

谢谢。

<!doctype html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
  <script>
    function calcIframeSize() {
      var altura = $("body", $("#frameExtraFields").contents()).height();
      $("#frameExtraFields").height(altura);
    }
    $(document).ready(function() {
      $("#frameExtraFields").ready( function() {
        calcIframeSize();
      });
    });
  </script>
</head>
<body>

<iframe src="frame.html" width="80%" height="600" id="frameExtraFields"></iframe>

</body>
</html>

【问题讨论】:

  • 预期结果是什么?
  • 你的问题来自$("#frameExtraFields").ready,并不代表iframe里面的文档被加载了。
  • 我尝试将就绪事件更改为加载事件,但没有成功。仅在 Chrome 和 Firefox 中不起作用。在 IE 中它可以正常工作。

标签: javascript jquery google-chrome iframe


【解决方案1】:

考虑到你的 iframe 在同一个域上加载了一个src,下面应该这样做:

<script>
    $(document).ready(function() {
        $('#frameExtraFields').load(function() {
            $(this).height($(this).contents().height());
        });
    });
</script>

<iframe src="/user/login/" width="80%" height="auto" id="frameExtraFields"></iframe>

请注意,我删除了您在 iframe 元素上设置的固定高度,并将其设置为 auto

this fiddle

【讨论】:

  • 我之前已经测试过了,但是还是不行。 ` `
【解决方案2】:

解决方案:

我对所有特别寻找chrome的浏览器使用以下代码:

.offsetHeight 在 chrome 中返回的值与其他浏览器中的 .scrollHeight 相同。

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

if (document.getElementById) {
    newheight = isChrome 
    ? document.getElementById(id).contentWindow.document.body.offsetHeight 
    : document.getElementById(id).contentWindow.document.body.scrollHeight;
}

调整 iframe 高度的完整功能:

function autoResize(id) //id = iframe-id
{
    var newheight = 500;
    var newwidth;

    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

    if (document.getElementById) {
        newheight = isChrome ? document.getElementById(id).contentWindow.document.body.offsetHeight : document.getElementById(id).contentWindow.document.body.scrollHeight;

        newheightVisible = newheight + 30; //Don't ask me why this, i am also wondering but it works
    }

    if (newheight != lastheight) {
        jQuery("#" + id).css('height', newheightVisible);
        lastheight = newheightVisible;
    }
}

【讨论】:

    猜你喜欢
    • 2016-09-11
    • 1970-01-01
    • 2011-10-13
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 2013-08-02
    相关资源
    最近更新 更多