contentWindow.document.body is null

contentWindow.document.body is null

本文关键字:null is body document contentWindow      更新时间:2023-09-26

我的javascript有一个问题,就是根据内容调整iFrame的大小。我让它在其他地方工作,但对于这个例子,它抛出了一个错误。使用以下代码,body为空,因此无法获得scrollHeight

if(document.getElementById('iFrameHelpDesk') != null)
{
    var Height = document.getElementById('iFrameHelpDesk').contentWindow.document.body.scrollHeight;
    document.getElementById('iFrameHelpDesk').height = Height + 40;
}

使用的html是:

<iframe src="http://<snipped webaddress>" id="iFrameHelpDesk" scrolling="no" frameborder="no"></iframe>

为什么这不会填充body对象?

我很简单地从文档加载($(function() {}))方法中获取代码,并将其放入它自己的方法中,以备实际iframe加载时使用。Ie.

$('#iFrameHelpDesk').load(function() {
    var Height = document.getElementById('iFrameHelpDesk').contentWindow.document.body.scrollHeight;
    document.getElementById(iFrameHelpDesk').height = Height + 40;
});

这是完美的,因为它应该。但现在我很困惑,为什么我对其执行类似代码的其他一些iframe在文档加载中运行良好。但这很有效,我对此很满意。