jQuery:添加delay()和removeClass()后,代码停止工作 [英] jQuery: code stops working after adding delay() and removeClass()

查看:83
本文介绍了jQuery:添加delay()和removeClass()后,代码停止工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码...

 $('nav ul li').hover(function() {

    $(this).addClass('hoverIn');


  },
  function() {

    $(this).addClass('hoverOut');


  });

效果很好.

但是当我添加delay()和removeClass()时,它不起作用,如下所示...

But when I add delay() and removeClass() it doesn't work, as follows...

 $('nav ul li').hover(function() {

    $(this).addClass('hoverIn').delay(800).removeClass('hoverIn');


  },
  function() {

    $(this).addClass('hoverOut').delay(800).removeClass('hoverOut');


  });

我在这里做错什么了吗?

Am I doing something wrong here?

任何帮助将不胜感激.谢谢.

Any help would be greatly appreciated. Thanks.

推荐答案

正如其他人所提到的,.removeClass()不是动画功能,因此不受任何排队效果的影响.

As others have mentioned, .removeClass() is not an animation function so is unaffected by any queued effects.

最简单的解决方案是使用.queue()将您的通话插入动画队列:

The simplest solution is to use .queue() to insert your call into the animation queue:

$(this).addClass('hoverIn').delay(800).queue(function() {
    $(this).removeClass('hoverIn').dequeue();
});

.dequeue()调用对于确保仍然有任何其他排队的操作很重要.

The .dequeue() call is important to ensure that any other queued operations still take place.

请注意,使用动画队列还意味着您可以使用.stop()取消操作(如果尚未发生).使用计时器会使批次更加复杂.

Note that using the animation queue also means that you can use .stop() to cancel the operation if it hasn't happened yet. Using timers would make that a lot more complicated.

如果您真的想花哨的话,我刚刚敲掉的这个插件将允许您将任何任意 jQuery函数添加到动画队列中:

If you want to get really fancy, this plugin I just knocked out will allow you to add any arbitrary jQuery function into the animation queue:

(function($) {
    $.fn.queued = function() {
        var self = this;
        var func = arguments[0];
        var args = [].slice.call(arguments, 1);
        return this.queue(function() {
            $.fn[func].apply(self, args).dequeue();
        });
    }
}(jQuery));

这样,上面的行将变为:

with this, the line above would become:

$(this).addClass('hoverIn').delay(800).queued('removeClass', 'hoverIn');

演示在 http://jsfiddle.net/alnitak/h5nWw/

这篇关于jQuery:添加delay()和removeClass()后,代码停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆