【问题标题】:jQuery - mouseenter / mouseleave with timer not functioningjQuery - mouseenter / mouseleave 计时器不起作用
【发布时间】:2016-10-17 21:34:34
【问题描述】:

我想要做的只是当有人在一个元素上悬停 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) 没有运行,并且没有删除类然后添加新的类。第二个(mouseleave)运行正常,确实删除了该类并添加了新的。

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

我能做些什么来解决这个问题?

【问题讨论】:

    标签: javascript jquery timer mouseenter


    【解决方案1】:

    我认为这是因为您在 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);
    });
    

    【讨论】:

    • 工作完美。
    【解决方案2】:

    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);
    })
    

    【讨论】:

      【解决方案3】:

      这里的问题是,您传递给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);
      });
      

      【讨论】:

        猜你喜欢
        • 2013-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多