jQuery和iFrame检测HTML注入后的新高度



我有一个iFrame,我正在像这样通过jQuery动态设置HTML。

$("#iframe").contents().find('body').html("This is a large HTML string");

效果很好。但现在我的高度无法调整iFrame的高度。我猜它是在DOM更改之前而不是之后获得高度的。现在如何使用新HTML获得新高度?我甚至不认为.load事件会触发。以下是我目前所拥有的:

$("#iframe").load(function () {
   //alerting this new height returns nothing
   $("#iframe").contents().find('body').height();
});

有什么想法吗?

使用方法链接

$("#iframe").contents().find('body').html("This is a large HTML string").height()
html方法根据作为参数传入的html设置内容。如果希望它激发load()事件,则应该使用load方法。此外,如果您不想依赖于事件,则可以将回调函数与load()一起使用。

由于您已经在使用jQuery,您可以创建一个回调函数,该函数将在iframe链完成后启动。只是一个演示,你可以从这里把它带到你想去的地方。

var callbacks = $.Callbacks();
callbacks.add( createIframe );
callbacks.fire( getHeight() );
function createIframe() {
 $("#iframe").contents().find('body').html("This is a large HTML  string");
}
function getHeight() {       
   alert( $("#iframe").contents().find('body').height() );
}

最新更新