Need help implementing the sequencing of jquery in

2019-08-20 22:02发布

The problem: I have a simple function and I need the instructions within it to take place one at a time. Here it is:

showImages = (current_time, exercise) ->
  $('#slideshow img.active').first().fadeOut(500).removeClass('active')
  $('#new-image').addClass('active')

Since the last 2 lines happen almost simultaneously, the image with id 'new-image' gets faded out.

I would like the line processing the img with the class 'active' to be completed before the next line kicks in.

I have done lots of Google searching but I don't know how to apply the code examples to this use case. Here are some Google articles I found:

Your help would be greatly appreciated.

3条回答
我想做一个坏孩纸
2楼-- · 2019-08-20 22:14

Use the fadeOut() complete function:

$('#slideshow img.active').first().fadeOut(500, function() {
  $(this).removeClass('active');
  $('#new-image').addClass('active');
});

Any code within the complete function is executed when the animation has finished

查看更多
神经病院院长
3楼-- · 2019-08-20 22:16

jQuery's fadeOut() method has a complete callback which can be used as a function:

.fadeOut( [duration ] [, complete ] )

This can be used as:

$(elem).fadeOut(500, function() { ... });

Therefore, in your case you can simply:

$('#slideshow img.active').first().fadeOut(500, function() {
    $(this).removeClass('active');
    $('#new-image').addClass('active');
});

With this, the currently .active element will lose its class and the #new-image will gain the active class after the fadeOut() has finished.

查看更多
Fickle 薄情
4楼-- · 2019-08-20 22:38

try this hope this helps. heres a quick jsFiddle

    $('#slideshow img.active').first()
    .fadeOut(500).removeClass('active')
    .setTimeout(function(){
      $('#new-image').addClass('active')
    },100);
查看更多
登录 后发表回答