根据.load() http://api.jquery.com/load-event/,事件应该触发,当
当元素和所有子元素完全加载时,加载事件将发送到该元素。该事件可以发送到任何元素与 URL 关联:图像、脚本、框架、iframe 和窗口对象。
因此,您不能将加载事件处理程序绑定到div
标签。当您希望在图像加载后触发事件处理程序时,必须将其绑定到图像
HTML:
<div id="content">
<!--this stuff takes a long time to load-->
<img id="large" src="http://lorempixel.com/1920/1920/">
</div>
<div id="loading">
<!-- this is the loading gif -->
<img src="http://lorempixel.com/400/200/">
</div>
JS:
// when user browses to page
$('#content').hide();
$('#loading').show();
// then when the #content div has loaded
$('#large').bind('load', function() {
$('#loading').hide();
$('#content').fadeIn('slow');
});
JSFiddle http://jsfiddle.net/Y9CQ4/1/
或者您可以将事件绑定到window
对象,当
该页面已完全加载,包括图形。
JS:
$(window).bind('load', function() {
$('#loading').hide();
$('#content').fadeIn('slow');
});
JSFiddle http://jsfiddle.net/Y9CQ4/2/
第三种方法是在加载事件触发时测试是否所有图像都已加载
function allImagesLoaded() {
var imgs = $(this).closest('div').find('img');
var loaded = 0;
imgs.each(function() { if ($(this.complete)) ++loaded; });
if (imgs.length == loaded) {
$('#loading').hide();
$('#content').fadeIn('slow');
}
}
// when user browses to page
$('#content').hide();
$('#loading').show();
// then when the #content div has loaded
$('#content img').bind('load', allImagesLoaded);
JSFiddle http://jsfiddle.net/Y9CQ4/3/