加载src-iframe的文档后调整其大小

Resizing a src iframe when its document has loaded?

本文关键字:调整 src-iframe 文档 加载      更新时间:2023-09-26

我们将phpBB嵌入到我们的网站中,为了嵌入效果良好,我们调整了加载phpBB的iFrame的高度。下面的代码运行良好,但并不完美。当帧的内容被重新加载(通过点击)时,它会等待.load()而不是.ready()来启动显示短暂延迟的调整大小事件。当你向下滚动示例中的页面并单击移动到另一个页面(例如,选择另一个论坛)时,你会注意到这一点。

我们尝试过使用$('frame').ready(),但它根本不起作用。

有什么好主意可以补救吗?请不要建议我们复制iFrame的内容或任何类似的东西。谢谢

function resize_iframes() {
    if ($('iframe').length < 1) return;
    // Set specific variable to represent all iframe tags.
    var iFrames = document.getElementsByTagName('iframe');
    // Resize heights.
    function iResize() {
        // Iterate through all iframes in the page.
        for (var i = 0, j = iFrames.length; i < j; i++) {
            // Set inline style to equal the body height of the iframed content.
            iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';
        }
    }
    // Check if browser is Safari or Opera.
    if ($.browser.safari || $.browser.opera) {
        // Start timer when loaded.
        $('iframe').load(function() {
            setTimeout(iResize, 0);
        });
    } else {
        // For other good browsers.
        $('iframe').load(function() {
            // Set inline style to equal the body height of the iframed content.
            try {
                this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
            } catch(err) {
            }
        });
    }
}

UPDATE请注意,可以通过更改自身内部的代码来更快地正确调整大小,并添加以下内容:

    window.setTimeout( function(){
        // Resize the frame we're in before it's fully loaded (images...)
        var iFrames = parent.document.getElementsByTagName('iframe');
        iFrames[0].style.height = iFrames[0].contentWindow.document.body.offsetHeight + 'px';
    }, 10 );

在脚本本身的某个地方。虽然它确实解决了我们的问题,但它并没有回答提出的问题,因此它保持开放状态,以防找到解决方案并应与公众分享。感谢:)

<iframe>没有类似于jQuery.ready()的事件。因此,要做到这一点,你必须自己触发一个事件。在所有子页面上包括此脚本:

var $ = window.parent.jQuery;
$(document).ready( function(){
    var iframe = window.frameElement;
    $(iframe).trigger("ready"); 
}); 

然后在带有iframe的页面上,您可以监听这样的就绪事件:

$("iframe").on("ready", function(){
    //iframe is ready
});