我可以延迟 jQuery addClass 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4836187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:00:40  来源:igfitidea点击:

Can I delay jQuery addClass?

jquerydelayaddclass

提问by Ryan

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

有没有办法延迟addClass()jQuery?例如这个代码

$('#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().

当我加载页面时,它已经在 id 'sampleID' 上有类 'aNewClass'。如何解决这个问题呢?我想要的是 addClass 将在结束fadeOut().

回答by Dave

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

您不能直接延迟 addClass 调用,但是如果您将它包装在一个队列调用中,该调用将一个函数作为这样的参数,则可以

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

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

请参阅这篇文章:jQuery:我可以在 addClass() 等之间调用 delay() 吗?

回答by Sarfraz

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

我想要的是 addClass 会在它结束 fakeOut() 后发生。

You can use callback function to fadeOutlike this:

您可以使用回调函数来fadeOut这样:

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

回答by lonesomeday

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

你不能这样做,delay因为它只影响效果队列。如果不是使用队列实现的,它不会“暂停”稍后代码的执行。

You need to do this with setTimeout:

你需要这样做setTimeout

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

This uses the completecallback of fadeOutand then sets a function to execute 2 seconds in the future.

这使用 的complete回调,fadeOut然后设置一个函数在未来 2 秒内执行。

回答by Arshdeep

You should use callbacks .

你应该使用回调。

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

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

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

回答by brandozz

You can also use setTimeout, with CSS transition :

您还可以使用 setTimeout 和 CSS 过渡:

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

And the CSS

和 CSS

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

#sampleID.aNewClass {
opacity: 1;
}