jQuery: Can I call delay() between addClass() and

2019-01-01 04:41发布

Something as simple as:

$("#div").addClass("error").delay(1000).removeClass("error");

doesn't seem to work. What would be the easiest alternative?

标签: jquery delay
8条回答
零度萤火
2楼-- · 2019-01-01 05:07

Try this:

function removeClassDelayed(jqObj, c, to) {    
    setTimeout(function() { jqObj.removeClass(c); }, to);
}
removeClassDelayed($("#div"), "error", 1000);
查看更多
还给你的自由
3楼-- · 2019-01-01 05:08

Delay operates on a queue. and as far as i know css manipulation (other than through animate) is not queued.

查看更多
琉璃瓶的回忆
4楼-- · 2019-01-01 05:11

I know this this is a very old post but I've combined a few of the answers into a jQuery wrapper function that supports chaining. Hope it benefits someone:

$.fn.queueAddClass = function(className) {
    this.queue('fx', function(next) {
        $(this).addClass(className);
        next();
    });
    return this;
};

And here's a removeClass wrapper:

$.fn.queueRemoveClass = function(className) {
    this.queue('fx', function(next) {
        $(this).removeClass(className);
        next();
    });
    return this;
};

Now you can do stuff like this - wait 1sec, add .error, wait 3secs, remove .error:

$('#div').delay(1000).queueAddClass('error').delay(2000).queueRemoveClass('error');

查看更多
裙下三千臣
5楼-- · 2019-01-01 05:13

jQuery's CSS manipulation isn't queued, but you can make it executed inside the 'fx' queue by doing:

$('#div').delay(1000).queue('fx', function() { $(this).removeClass('error'); });

Quite same thing as calling setTimeout but uses jQuery's queue mecanism instead.

查看更多
其实,你不懂
6楼-- · 2019-01-01 05:14

You can create a new queue item to do your removing of the class:

$("#div").addClass("error").delay(1000).queue(function(next){
    $(this).removeClass("error");
    next();
});

Or using the dequeue method:

$("#div").addClass("error").delay(1000).queue(function(){
    $(this).removeClass("error").dequeue();
});

The reason you need to call next or dequeue is to let jQuery know that you are done with this queued item and that it should move on to the next one.

查看更多
孤独总比滥情好
7楼-- · 2019-01-01 05:14

Of course it would be more simple if you extend jQuery like this:

$.fn.addClassDelay = function(className,delay) {
    var $addClassDelayElement = $(this), $addClassName = className;
    $addClassDelayElement.addClass($addClassName);
    setTimeout(function(){
        $addClassDelayElement.removeClass($addClassName);
    },delay);
};

after that you can use this function like addClass:

$('div').addClassDelay('clicked',1000);
查看更多
登录 后发表回答