开发者

Can I delay jQuery addClass?

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().


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?


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');
});


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.


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;
}


You should use callbacks .

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜