gpt4 book ai didi

dom中所有图像加载后jquery回调?

转载 作者:行者123 更新时间:2023-12-03 21:27:52 25 4
gpt4 key购买 nike

加载 DOM 中的所有图像后如何触发事件?我用谷歌搜索了很多。我发现了这个,但似乎不起作用:

jQuery event for images loaded

最佳答案

使用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com