我的 javascript 有一个问题,就是根据内容调整 iFrame 的大小。我让它在其他地方工作,但对于这个例子,它抛出一个错误。使用以下代码body为 null,因此无法获取scrollHeight。
if(document.getElementById('iFrameHelpDesk') != null)
{
var Height = document.getElementById('iFrameHelpDesk').contentWindow.document.body.scrollHeight;
document.getElementById('iFrameHelpDesk').height = Height + 40;
}
Run Code Online (Sandbox Code Playgroud)
使用的html是:
<iframe src="http://<snipped webaddress>" id="iFrameHelpDesk" scrolling="no" frameborder="no"></iframe>
Run Code Online (Sandbox Code Playgroud)
为什么这不填充body对象?
相当简单的是,我从文档 load () 方法中获取代码$(function() {}),并将其放入它自己的方法中,以便在实际 iframe 加载时使用。IE。
$('#iFrameHelpDesk').load(function() {
var Height = document.getElementById('iFrameHelpDesk').contentWindow.document.body.scrollHeight;
document.getElementById(iFrameHelpDesk').height = Height + 40;
});
Run Code Online (Sandbox Code Playgroud)
这很完美,正如它应该的那样。但现在让我感到困惑的是,为什么我执行类似代码的其他一些 iframe 在文档加载中工作得很好。但这确实有效,我对此很满意。