jQuery: code stops working after adding delay() and removeClass()

后端 未结 3 877
太阳男子
太阳男子 2020-12-11 11:27

Here\'s my code...

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

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


  },
  function() {

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


  })         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 11:55

    .delay() only works with jQuery methods that use the animation queue, thus is does not work with removeClass().

    The removeClass() operation will still be performed, but it will be performed immediately, not after the delay time.

    So, when you do:

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

    that is the same as:

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

    which is the same as doing nothing, thus you see not effect.


    You can solve your problem with setTimeout() like this:

     $('nav ul li').hover(function() {
        var self = $(this).addClass('hoverIn');
        setTimeout(function() {self.removeClass('hoverIn');}, 800);
      }, function() {
        var self = $(this).addClass('hoverOut');
        setTimeout(function() {self.removeClass('hoverOut');}, 800);
      });
    

    Or, using a common function, like this:

    jQuery.fn.addClassTemporary = function(cls, t) {
        var self = this.addClass(cls);
        setTimeout(function() {self.removeClass(cls);}, t);
    }
    
     $('nav ul li').hover(function() {
         $(this).addClassTemporary('hoverIn', 800);
     }, function() {
         $(this).addClassTemporary('hoverOut', 800);
     });
    

提交回复
热议问题