Dee*_*Dee 43 jquery load image
如何加载DOM中的所有图像时触发事件?我google了很多.我发现了这个,但它似乎不起作用:
use*_*716 113
使用load()(docs)方法对抗window.
$(window).load(function() {
// this will fire after the entire page is loaded, including images
});
Run Code Online (Sandbox Code Playgroud)
或者直接通过window.onload.
window.onload = function() {
// this will fire after the entire page is loaded, including images
};
Run Code Online (Sandbox Code Playgroud)
如果要为每个图像触发单独的事件,请在每个图像上放置一个.load().
$(function() {
$('img').one('load',function() {
// fire when image loads
});
});
Run Code Online (Sandbox Code Playgroud)
或者,如果有可能缓存图像,请执行以下操作:
$(function() {
function imageLoaded() {
// function to invoke for loaded image
}
$('img').each(function() {
if( this.complete ) {
imageLoaded.call( this );
} else {
$(this).one('load', imageLoaded);
}
});
});
Run Code Online (Sandbox Code Playgroud)
编辑:
要在最后一个图像加载后执行某些操作,请使用计数器设置总图像数,并在每次调用加载处理程序时递减.
当它到达时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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
下面是我提出的,使用延迟对象而$.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 */
});
Run Code Online (Sandbox Code Playgroud)
如果有任何警告,请告诉我.
使用user113716的编辑解决方案遇到的一个问题是,破碎的图像会使计数器永远不会达到0.这对我来说是固定的.
.error(function(){
imageLoaded();
$(this).hide();
});
Run Code Online (Sandbox Code Playgroud)