我可以延迟 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
Can I delay jQuery addClass?
提问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?
回答by Sarfraz
What I want is the addClass will happen after it ended the fadeOut().
我想要的是 addClass 会在它结束 fakeOut() 后发生。
You can use callback function to fadeOut
like this:
您可以使用回调函数来fadeOut
这样:
$('#sampleID').fadeOut(500, function(){
$(this).addClass('aNewClass');
});
回答by lonesomeday
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.
你不能这样做,delay
因为它只影响效果队列。如果不是使用队列实现的,它不会“暂停”稍后代码的执行。
You need to do this with setTimeout
:
你需要这样做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.
这使用 的complete
回调,fadeOut
然后设置一个函数在未来 2 秒内执行。
回答by Arshdeep
You should use callbacks .
你应该使用回调。
$('#sampleID').delay(2000).fadeOut(500,function(){
$(this).delay(2000).addClass('aNewClass');
});
回答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;
}