【发布时间】:2011-06-18 23:27:57
【问题描述】:
如何在加载 DOM 中的所有图像时触发事件? 我用谷歌搜索了很多。我找到了这个,但它似乎不起作用:
【问题讨论】:
如何在加载 DOM 中的所有图像时触发事件? 我用谷歌搜索了很多。我找到了这个,但它似乎不起作用:
【问题讨论】:
对window 使用load()(docs) 方法。
$(window).load(function() {
// this will fire after the entire page is loaded, including images
});
注意:在较新的 jQuery 版本上使用 $(window).on('load', function(){ ...});
或者直接通过window.onload 进行操作。
window.onload = function() {
// this will fire after the entire page is loaded, including images
};
如果您想为每张图片触发一个单独的事件,请在每张图片上放置一个.load()。
$(function() {
$('img').one('load',function() {
// fire when image loads
});
});
或者,如果有可能缓存图像,请执行以下操作:
$(function() {
function imageLoaded() {
// function to invoke for loaded image
}
$('img').each(function() {
if( this.complete ) {
imageLoaded.call( this );
} else {
$(this).one('load', imageLoaded);
}
});
});
编辑:
为了在最后一张图片加载后执行一些操作,使用一个设置为图片总数的计数器,并在每次调用加载处理程序时递减。
当它到达0 时,运行一些其他代码。
$(function() {
function imageLoaded() {
// function to invoke for loaded image
// decrement the counter
counter--;
if( counter === 0 ) {
// counter is 0 which means the last
// one loaded, so do something else
}
}
var images = $('img');
var counter = images.length; // initialize the counter
images.each(function() {
if( this.complete ) {
imageLoaded.call( this );
} else {
$(this).one('load', imageLoaded);
}
});
});
【讨论】:
load 事件似乎并没有让 DOM 冒泡。为了让它对我有用,我必须将事件直接附加到图像上。因此,不要使用$parent.on('load', 'img', doSmthg) 来捕获$parent 下的所有图像,使用事件传播。
下面是我想出的,使用 deferred 对象和$.when 而不是使用计数器。
var deferreds = [];
$('img').each(function() {
if (!this.complete) {
var deferred = $.Deferred();
$(this).one('load', deferred.resolve);
deferreds.push(deferred);
}
});
$.when.apply($, deferreds).done(function() {
/* things to do when all images loaded */
});
如果有任何警告,请告诉我。
【讨论】:
我在使用 user113716 的编辑解决方案时遇到的一个问题是,损坏的图像会使计数器永远不会达到 0。这为我解决了这个问题。
.error(function(){
imageLoaded();
$(this).hide();
});
【讨论】:
images.error 才能完成这项工作,但现在它似乎运作良好。谢谢!