无法通过jquery选择在图片库中循环

问题描述:

jQuery中的Noob.

Noob in jQuery.

我正在尝试浏览图像库,以使图像淡入和淡出.

I'm trying to cycle through an image gallery with the goal of having the images fade in and fade out.

这是我的 JSFiddle
通过单击#gallery,每个图像fadeTo(arg1),然后fadeTo(args2).
但我希望他们一个一个地走.
也许应该在链中添加delay?

Here is my JSFiddle
By clicking on #gallery each image fadeTo(arg1) and then fadeTo(args2).
But I want them to go one by one.
Perhaps a delay should be added to the chain?

任何帮助将不胜感激.

jQuery动画(与javascript中的大多数事情一样)是异步的,这意味着函数调用在操作完成之前返回.从某种意义上讲,您可以想到$('img').each循环的每次迭代如下:

jQuery animations (as most things on javascript) are asynchronous, which means that the function calls return before the action has finished. In a sense, you can think of each iteration of your $('img').each loop as following:

  • jQuery使用绑定到一个img元素的this调用您的函数
  • 您的函数在$(this)上调用fade
  • jQuery然后要求浏览器安排要运行的动画
  • 您的函数返回
  • jQuery calls your function with this bound to one img element
  • Your function calls fade on $(this)
  • jQuery then asks the browser to schedule an animation to be run
  • Your function returns

然后, 结束后,浏览器将开始使动画同时在屏幕上发生(因为所有动画均已安排).

Then, after all your iterations have ended the browser will start to make the animations happen on the screen, all at the same time (since all of them were scheduled).

要创建顺序行为,可以为fade函数提供回调:

To create a sequential behavior, you can give the fade function a callback:

$('#gallery').click(function(evt) {
  var remainingImages = $("img").toArray();

  var processNext = function() {
    var image = remainingImages.shift();
    if(!image) return;

    // Add the next iteration as a callback to the animation
    $(image).fadeTo(500, .3).fadeTo(250, 1, processNext);
  };

  processNext();
});

然后,发生的事情是这样的,而不是立即安排所有动画:

Then, instead of scheduling all animations at once, what happens is something like this:

  • 所有当前img元素都存储在remainingImages数组中
  • 调用processNext函数,该函数从数组中删除第一张图像
  • 该函数在$(image)上调用fade,提供了一个函数(恰好是它本身),该函数应在动画制作完成后 调用.
  • jQuery使用浏览器安排动画,并告诉动画随后执行功能
  • 动画结束后,将执行下一个迭代
  • All the current img elements are stored in the remainingImages array
  • The processNext function is called, which removes the first image from the array
  • The function calls fade on the $(image), providing a function (that happens to be itself) that should be called after the animation is finished
  • jQuery schedules the animation with the browser, and tells it to execute the function afterwards
  • After the animation finishes, the next iteration is executed

更新了jsFiddle