jQuery的.如何使用queue()与使用回调函数完成某些事情?

gil*_*ero 7 javascript queue jquery jquery-callback

HTML:

<span>hello world!</span>
Run Code Online (Sandbox Code Playgroud)

js :(使用回调)

$('span').click(function() {
  $(this).animate({
    fontSize: '+=10px'
  }, 'slow', function() {
    // callback after fontsize increased
    $(this).text(  $(this).text() + ' rolled! ' );
  });
});
Run Code Online (Sandbox Code Playgroud)

因此,每次SPAN单击时,在字体大小增加后附加文本"滚动",而不是一起发生.

它可以通过使用queue()来完成,如下所示:

js :(使用queue())

$('span').click(function() {
  $(this).animate({
    fontSize: '+=10px'
  }, 'slow'})
  .queue(function() {
    $(this).text(  $(this).text() + ' rolled! ' );
  });
});
Run Code Online (Sandbox Code Playgroud)

我不确定它们之间有什么区别.都做同样的事情.

为什么queue()比使用回调更好/更喜欢(或者为什么不是)?queue()有什么特别之处?

谢谢.

idd*_*ddo 1

您可以将更多事件(您在代码中其他指定的事件)放入动画所在的同一队列中。

因此,回调将在动画准备好后立即执行,但在使用queue()的情况下,队列中可能有其他事件将首先执行。

这种行为的优点是不会同时执行并发事件(例如向上滑动和向下滑动),这会产生奇怪的结果。

例子:

$('div').click(function() {
  $(this).animate({
    color: 'green'
  }, 'slow'})
  .queue(function() {
    $(this).text( ' got colored! ' );
  });
});

$('span').click(function() {
  $(this).animate({
    fontSize: '+=10px'
  }, 'slow'})
  .queue(function() {
    $(this).text(  ' got bigger! ' );
  });
});
Run Code Online (Sandbox Code Playgroud)

如果您先单击 div,然后立即单击 span,那么现在您可以确定 div 的队列将首先执行,当准备就绪时,span 的队列将被执行。

如果发生回调,则首先执行属于先准备好的动画的回调。如果它们同时准备好,那么它们就会同时执行。在这种情况下,这将导致看不到“有颜色!” 文字或“变大了!” 文本。