【发布时间】:2011-04-09 21:46:45
【问题描述】:
加载页面中的所有图像后如何运行 jQuery 代码?
【问题讨论】:
标签: javascript jquery html image
加载页面中的所有图像后如何运行 jQuery 代码?
【问题讨论】:
标签: javascript jquery html image
$(window).load(function(){})
【讨论】:
检查所有 图像 是否已加载有点复杂,因此除非您迫切需要如此精确,否则检查所有图像和其他所有内容是否已加载要容易得多:
$(window).load(function() { ... });
这利用了 jQuery .load() 方法。
如果您确实需要仅检查特定图像,那么事情会变得有些棘手。我最初想这样做:
$("img").load(function() { ... }); \\ THIS IS INCORRECT!!!!!
然而,上面创建了一个包含所有图像的 jQuery 对象,然后它将function() { ... } 绑定到这些图像中的每个。所以上面会触发一个函数的次数和页面上的图片一样多!
为了解决这个问题,我们应该检查页面上有多少张图片,并且只在所有图片加载完成后触发一次函数:
$(function() {
// To keep track of how many images have loaded
var loaded = 0;
// Let's retrieve how many images there are
var numImages = $("img").length;
// Let's bind a function to the loading of EACH image
$("img").load(function() {
// One more image has loaded
++loaded;
// Only if ALL the images have loaded
if (loaded === numImages) {
// This will be executed ONCE after all images are loaded.
function() { ... }
}
});
});
【讨论】:
load。
$(function() {
var length = $('img').length ;
var counter = 0;
$('img').each(function() {
$(this).load(function(){
counter++;
if(counter == length) {
Callback(); //do stuff
}
});
});
});
【讨论】:
$("img").load() 而不是 $("img").each(function() { $(this).load() }) 删除一行 - 请参阅我编辑的答案。
我最近做了类似的事情,但做了不同的事情。
$('img').on('load', function(){
$('img').off('load'); //detaches from load event, so code below only executes once
// my code to execute
});
【讨论】:
不是直接的答案。还是值得参考的。
参考
代码
$(window).bind("load", function() {
// code here
});
【讨论】:
@Peter Ajtai 的答案除了在 IE 的缓存图像上有效。要使其与 IE 一起使用,有一个解决方案:https://stackoverflow.com/a/3877079 或使用imagesLoaded 插件。
【讨论】:
对于任何使用 jquery 的人来说,这个小 sn-p 可以解决问题(它确保在运行其中的任何脚本之前加载所有图像)...
$(window).bind("load", function() {
// code goes here here
});
【讨论】: