我正在尝试加载我的图像并淡入。它正在工作。但是让我们假设我有 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;
});
});
最佳答案
参见 http://jsfiddle.net/5uNGR/15/
尝试一些你不尝试在每个图像加载时执行淡入的方法,而是在每次发生任何加载事件时测试动画队列中下一个图像的 ok-ness,然后在动画回调上,看看是否下一个准备好了。这是一个应该可以工作的脚本。
顺便说一句,请参阅 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;
});
});
关于javascript - 加载图像并淡入,但以顺序方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13676419/