jQuery - 带有计时器的 mouseenter / mouseleave 不工作

jQuery - mouseenter / mouseleave with timer not functioning

我想做的只是 运行 当有人在某个元素上悬停 1 秒时我的代码。

这是我正在使用的代码:

var timer;

$(".homeLinkWrap").mouseenter(function() {
  timer = setTimeout(function(){
   $(this).find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({opacity: '1'});
    console.log('in');
  }, 1000);
}).mouseleave(function() {
    $(this).find('.homeLinkNfo').removeClass('flipInY').addClass('flipOutY');
    console.log('out');
    clearTimeout(timer);
});

第一部分(mouseenter)无法正常工作并且不会删除 class 然后添加新的。第二个(mouseleave)功能正常,确实删除了 class 并添加了新的。

我猜这是因为我的目标是 $(this),它是悬停在上面的当前元素,因为它在计时器函数中 jQuery 不知道 $(this) 是哪个元素参考。

我该怎么做才能解决这个问题?

我认为这是因为您在 setTimeout 函数中调用了 $(this) 。你需要做这样的事情:

$(".homeLinkWrap").mouseenter(function() {
    var $self = $(this);
    timer = setTimeout(function(){
       $self.find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({opacity: '1'});
       console.log('in');
    }, 1000);
});

setTimeout 回调中,this 不再引用 jQuery 选择。您应该保留对选择的引用:

$(".homeLinkWrap").mouseenter(function() {
  var $this = $(this);
  timer = setTimeout(function(){
     $this.find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({opacity: '1'});
    console.log('in');
  }, 1000);
})

或者使用箭头函数(ES2015)

$(".homeLinkWrap").mouseenter(function() {
  timer = setTimeout(() => {
   $(this).find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({opacity: '1'});
    console.log('in');
  }, 1000);
})

这里的问题是,您传递给 setTimeout 的回调函数中的 this 与回调外部的 this 引用的点不同.

有一些方法可以解决您的问题,我建议您使用 Function.prototype.bind 将您的回调函数绑定到与外部相同的 this

var timer;

$(".homeLinkWrap").mouseenter(function() {
  timer = setTimeout((function() {
    $(this).find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({ opacity: '1' });
  }).bind(this), 1000);
}).mouseleave(function() {
  $(this).find('.homeLinkNfo').removeClass('flipInY').addClass('flipOutY');
  clearTimeout(timer);
});