jquery 在加载时获取 iframe 内容的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3846132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:13:28  来源:igfitidea点击:

jquery get height of iframe content when loaded

jqueryiframeheightonload

提问by FFish

I have a Help page, help.php that I am loading inside an iframe in main.php How can I get the height of this page once it has loaded in the iframe?

我有一个帮助页面 help.php,我正在 main.php 中的 iframe 中加载它,一旦它加载到 iframe 中,如何获取此页面的高度?

I am asking this because I can't style the height of to iframe to 100% or auto. That's why I think I need to use javascript.. I am using jQuery

我问这个是因为我无法将 iframe 的高度设置为 100% 或自动。这就是为什么我认为我需要使用 javascript.. 我正在使用 jQuery

CSS:

CSS:

body {
    margin: 0;
    padding: 0;
}
.container {
    width: 900px;
    height: 100%;
    margin: 0 auto;
    background: silver;
}
.help-div {
    display: none;
    width: 850px;
    height: 100%;
    position: absolute;
    top: 100px;
    background: orange;
}
#help-frame {
    width: 100%;
    height: auto;
    margin:0;
    padding:0;
}

JS:

JS:

$(document).ready(function () {
    $("a.open-help").click(function () {
        $(".help-div").show();
        return false;
    })
})

HTML:

HTML:

<div class='container'>
    <!-- -->
    <div class='help-div'>
        <p>This is a div with an iframe loading the help page</p>
        <iframe id="help-frame" src="../help.php" width="100%" height="100%" frameborder="1"></iframe>
    </div>  <a class="open-help" href="#">open Help in iFrame</a>

    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
</div>

回答by FFish

ok I finally found a good solution:

好的,我终于找到了一个很好的解决方案:

$('iframe').load(function() {
    this.style.height =
    this.contentWindow.document.body.offsetHeight + 'px';
});

Because some browsers (older Safari and Opera) report onload completed before CSS renders you need to set a micro Timeout and blank out and reassign the iframe's src.

因为某些浏览器(旧版 Safari 和 Opera)在 CSS 呈现之前报告加载完成,您需要设置微超时并清空并重新分配 iframe 的 src。

$('iframe').load(function() {
    setTimeout(iResize, 50);
    // Safari and Opera need a kick-start.
    var iSource = document.getElementById('your-iframe-id').src;
    document.getElementById('your-iframe-id').src = '';
    document.getElementById('your-iframe-id').src = iSource;
});
function iResize() {
    document.getElementById('your-iframe-id').style.height = 
    document.getElementById('your-iframe-id').contentWindow.document.body.offsetHeight + 'px';
}

回答by Andrew

The less complicated answer is to use .contents()to get at the iframe. Interestingly, though, it returns a different value from what I get using the code in my original answer, due to the padding on the body, I believe.

不太复杂的答案是.contents()用于获取 iframe。有趣的是,它返回的值与我在原始答案中使用代码得到的值不同,我相信这是由于主体上的填充。

$('iframe').contents().height() + 'is the height'


This is how I've done it for cross-domain communication, so I'm afraid it's maybe unnecessarily complicated. First, I would put jQuery inside the iFrame's document; this will consume more memory, but it shouldn't increase load time as the script only needs to be loaded once.

这就是我为跨域通信所做的,所以恐怕它可能不必要地复杂。首先,我将 jQuery 放在 iFrame 的文档中;这将消耗更多内存,但不应增加加载时间,因为脚本只需要加载一次。

Use the iFrame's jQuery to measure the height of your iframe's body as early as possible (onDOMReady) and then set the URL hash to that height. And in the parent document, add an onloadevent to the iFrame tag that will look at the location of the iframe and extract the value you need. Because onDOMReady will always occur before the document's load event, you can be fairly certain the value will get communicated correctly without a race condition complicating things.

使用 iFrame 的 jQuery 尽早测量 iframe 主体的高度 (onDOMReady),然后将 URL 哈希设置为该高度。在父文档中,onload向 iFrame 标记添加一个事件,该事件将查看 iframe 的位置并提取您需要的值。因为 onDOMReady 将始终发生在文档的加载事件之前,所以您可以相当确定该值将被正确传达,而不会出现竞争条件使事情变得复杂。

In other words:

换句话说:

...in Help.php:

...在 Help.php 中:

var getDocumentHeight = function() {
    if (location.hash === '') { // EDIT: this should prevent the retriggering of onDOMReady
        location.hash = $('body').height(); 
        // at this point the document address will be something like help.php#1552
    }
};
$(getDocumentHeight);

...and in the parent document:

...在父文档中:

var getIFrameHeight = function() {
    var iFrame = $('iframe')[0]; // this will return the DOM element
    var strHash = iFrame.contentDocument.location.hash;
    alert(strHash); // will return something like '#1552'
};
$('iframe').bind('load', getIFrameHeight );

回答by Hyman Zach Tibbles

I found the following to work on Chrome, Firefox and IE11:

我发现以下内容适用于 Chrome、Firefox 和 IE11:

$('iframe').load(function () {
    $('iframe').height($('iframe').contents().height());
});

When the Iframes content is done loading the event will fire and it will set the IFrames height to that of its content. This will only work for pages within the same domain as that of the IFrame.

当 Iframes 内容加载完毕后,该事件将触发,并将 IFrames 高度设置为其内容的高度。这仅适用于与 IFrame 相同域中的页面。

回答by cchamberlain

The code to do this without jQuery is trivial nowadays:

现在,在没有 jQuery 的情况下执行此操作的代码是微不足道的:

const frame = document.querySelector('iframe')
function syncHeight() {
  this.style.height = `${this.contentWindow.document.body.offsetHeight}px`
}
frame.addEventListener('load', syncHeight)

To unhook the event:

解开事件:

frame.removeEventListener('load', syncHeight)

回答by RkaneKnight

You don't need jquery inside the iframe to do this, but I use it cause the code is so much simpler...

您不需要在 iframe 中使用 jquery 来执行此操作,但我使用它是因为代码要简单得多...

Put this in the document inside your iframe.

将其放在 iframe 内的文档中。

$(document).ready(function() {
  parent.set_size(this.body.offsetHeight + 5 + "px");  
});

added five above to eliminate scrollbar on small windows, it's never perfect on size.

在上面添加了五个以消除小窗口上的滚动条,它的大小永远不会完美。

And this inside your parent document.

这在您的父文档中。

function set_size(ht)
{
$("#iframeId").css('height',ht);
}

回答by Javier Gordo

this is the correct answer that worked for me

这是对我有用的正确答案

$(document).ready(function () {
        function resizeIframe() {
            if ($('iframe').contents().find('html').height() > 100) {
                $('iframe').height(($('iframe').contents().find('html').height()) + 'px')
            } else {
                setTimeout(function (e) {
                    resizeIframe();
                }, 50);
            }
        }
        resizeIframe();
    });

回答by Pixelomo

simple one-liner starts with a default min-height and increases to contents size.

简单的单行以默认的最小高度开始并增加到内容大小。

<iframe src="http://url.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>

回答by Ryan J. Stout

Accepted answer's $('iframe').loadwill now produce a.indexOf is not a functionerror. Can be updated to:

接受的答案$('iframe').load现在会产生a.indexOf is not a function错误。可以更新为:

$('iframe').on('load', function() {
  // ...
});

Few others similar to .loaddeprecated since jQuery 1.8: "Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

很少有其他类似.load自 jQuery 1.8 以来已弃用的内容:打开新的基础项目时出现“Uncaught TypeError: a.indexOf is not a function”错误

回答by Envil

This's a jQuery free solution that can work with SPA inside the iframe

这是一个 jQuery 免费解决方案,可以在 iframe 中使用 SPA

document.getElementById('iframe-id').addEventListener('load', function () {
  let that = this;
  setTimeout(function () {
    that.style.height = that.contentWindow.document.body.offsetHeight + 'px';
  }, 2000) // if you're having SPA framework (angularjs for example) inside the iframe, some delay is needed for the content to populate
});