简体   繁体   English

为什么我不能使用jquery延迟addClass和removeClass?

[英]why can't I delay addClass and removeClass using jquery?

This is my code: 这是我的代码:

   $("#form_editor").addClass('abcd')
   $("#form_editor").delay(32000).removeClass('abcd')

The class never gets applied if I have the second line uncommented . 如果我没有取消注释第二行,则该类永远不会被应用。 If I comment it out, then the class gets applied as expected. 如果我将其注释掉,那么该类将按预期应用。 It seems that the second line executes without any delay at all ie ignores .delay(32000) . 似乎第二行完全没有任何延迟地执行,即忽略.delay(32000)

Does delay work with addClass and removeClass ? 延迟是否适用于addClassremoveClass I assumed it would delay the call to any function that came after it, but apparently not as it seems to execute right away. 我认为它会延迟对它之后出现的任何函数的调用,但显然不是因为它似乎立即执行。

You can, but you need to queue() 你可以,但你需要queue()

 $("#form_editor").addClass('abcd').delay(3200).queue(function() { $(this).removeClass('abcd'); }); 
 .abcd:before{ content:"abcd"; background:red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="form_editor">efgh....</div> 

or use setTimeout method: 或使用setTimeout方法:

 var $formEditor = $("#form_editor"); // we plan to reuse it so let's cache it! $formEditor.addClass('abcd'); // add setTimeout(function(){ $formEditor.removeClass('abcd'); // remove }, 3200); 
 .abcd:before{ content:"abcd"; background:red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="form_editor">efgh....</div> 

jQuery animations (.animate, .fadeTo, fadeIn, etc...) add to the animation queue stack, an jQuery internal function than handles "what's next?" jQuery动画(.animate,.fadeTo,fadeIn等...)添加到动画队列堆栈,一个jQuery内部函数,而不是处理“下一步是什么?” (laically speaking), while other "animation-less" methods (like .text(), addClass(), .on(), .click() etc...) do not. (懒散地说),而其他“无动画”方法(如.text(),addClass(),. on(),。click()等...)则没有。

To easily remember .queue() think of it as the missing (really is) callback functionality for .delay(2000, function(){ /*BAM!*/ }) /* well sadly, this does not works */ 为了容易记住.queue()将其视为.delay(2000, function(){ /*BAM!*/ }) /* well sadly, this does not works */的缺失(实际上)回调功能, .delay(2000, function(){ /*BAM!*/ }) /* well sadly, this does not works */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM