加载 DOM 中的所有图像后如何触发事件? 我用谷歌搜索了很多。我发现了这个,但似乎不起作用:
最佳答案
使用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);
}
});
});
关于dom中所有图像加载后jquery回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4857896/