Can I delay jQuery addClass?

2019-03-18 18:00发布

问题:

Is there a way to delay the addClass() of jQuery? For example this code

$('#sampleID').delay(2000).fadeOut(500).delay(2000).addClass('aNewClass');

When I load the page, it has the class 'aNewClass' already on id 'sampleID'. How to solve this problem? What I want is the addClass will happen after it ended the fadeOut().

回答1:

What I want is the addClass will happen after it ended the fadeOut().

You can use callback function to fadeOut like this:

$('#sampleID').fadeOut(500, function(){
  $(this).addClass('aNewClass');
});


回答2:

You can't directly delay an addClass call, however you can if you wrap it in a queue call which takes a function as a parameter like this

$(this).delay(2000).queue(function(){$(this).addClass('aNewClass')});

See this post: jQuery: Can I call delay() between addClass() and such?



回答3:

You can't do this with delay because it only affects the effects queue. It doesn't "pause" execution of later code if it is not implemented using the queue.

You need to do this with setTimeout:

$('#sampleID').delay(2000).fadeOut(500, function() {
    setTimeout(function() {
        $(this).addClass('aNewClass');
    }, 2000);
});

This uses the complete callback of fadeOut and then sets a function to execute 2 seconds in the future.



回答4:

You should use callbacks .

$('#sampleID').delay(2000).fadeOut(500,function(){
   $(this).delay(2000).addClass('aNewClass');
});

http://api.jquery.com/fadeOut/



回答5:

You can also use setTimeout, with CSS transition :

setTimeout(function() {
    $('#sampleID').addClass('aNewClass');
}, 2000);

And the CSS

#sampleID {
transition: opacity 1s ease;
opacity: 0;
}

#sampleID.aNewClass {
opacity: 1;
}