我正在尝试加载我的图像并淡入。它正在工作。但我们假设我有4张图片。现在,我的脚本通过加载最后一个图像来工作,而不是第一个。如何让我的js加载第一个图像,并在加载第一个图像后开始加载第二个图像?
这是我的代码:
$(function(){
$("a").click(function(){
$("#load").load('load.html', function() {
$('#load img').hide();
alert($("#load img").length);
$('#load img').each( function(){
$(this).on('load', function () {
$(this).fadeIn();
});
});
});
return false;
});
});
答案 0 :(得分:1)
请参阅http://jsfiddle.net/5uNGR/15/
尝试在每个图像加载时不尝试对每个图像执行淡入淡出的操作,但每次发生任何加载事件时测试动画队列中下一个图像的确定性,然后在动画回调中查看是否有效下一个准备好了。这是一个应该有效的脚本。
BTW,有关图像准备测试的更多信息,请参阅http://www.sajithmr.me/javascript-check-an-image-is-loaded-or-not。
$(function () {
// util fn to test if image loaded properly
var isImgLoadOk = function (img) {
if (!img.complete) { return false; }
if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
return false;
}
return true;
};
$("a").on('click', function () {
$("#load").load('load.html', function () {
var imgs = $('#load img').hide(), //create image array and hide (chaining)
animIndex = 0, //position in the animation queue
isFading = false; //track state of whether an animation is in prog
// this is a load handler AND is called in the fadeIn callback if
// not at last image in the collection
var fadeNextImg = function () {
// make sure a load event didn't happen in the middle of an animation
if (isFading) return;
// last image in animation queue?
var isLast = animIndex == imgs.length - 1;
// get the raw image out of the collection and test if it is loaded happily
var targetImage = imgs[animIndex];
if (isImgLoadOk(targetImage)) {
// jQuery-up the htmlImage
targetImage = $(targetImage);
// increment the queue
animIndex++;
// set animation state - this will ignore load events
isFading = true;
// fade in the img
targetImage.fadeIn('slow', function () {
isFading = false;
// test to see if next image is ready to load by
// recursively calling the parent fn
if (!isLast) fadeNextImg();
});
}
};
imgs.on('load', fadeNextImg);
});
return false;
});
});
答案 1 :(得分:0)
$(function(){
$("a").click(function(){
$("#load").load('load.html', function() {
$('#load img').hide(); // I would recommend using css to hide the image instead
alert($("#load img").length);
$("#load img").each(function(i, image) {
setTimeout(function() { // For each image, set increasingly large timeout before fadeIn
$(this).fadeIn();
}, 2000 * i);
});
});
return false;
});
});