【问题标题】:execute Jquery when the mouse stops moving当鼠标停止移动时执行 Jquery
【发布时间】:2013-06-22 15:53:02
【问题描述】:

我有一个快速脚本,它有一个跟随光标的轨迹:

jQuery(document).ready(function(){
   $(document).mousemove(function(e){
       $('.fall').each(function(){
           if ($(this).css("opacity") == 0){
               $(this).remove();
           };
       });
       t = (e.pageY - 10).toString() + 'px';
       l = (e.pageX - 10).toString() + 'px';
       $('.fall').css("margin_left",l);
       $('.fall').css("margin_top",t);
       var doit = '<div class="fall" style="position:fixed;margin-left:' + l + ';margin-top:' + t + ';">+</div>'
       $('body').prepend(doit);
      $('#status2').html(e.pageX +', '+ e.pageY);

       $('.fall').animate({
           marginTop: '+=50px',
           opacity: 0
       },1000);       
   }); 
});

现在我想删除animate 部分,并在鼠标不移动时有如下内容:

$('.fall').each(function(){
    $(this).fadeOut('slow');
    $(this).remove()
});

当鼠标超过一秒钟没有移动时,我只是不知道如何执行此操作。有什么想法吗?

谢谢,here is a jsfiddle

【问题讨论】:

  • 每次移动时更新一个 var mouseLastMoved 并使用 setTimeout 来检查 now &gt; mouseLastMoved + x seconds?
  • 我不太明白你想要什么,但我更新了它以使用你的新代码:jsfiddle.net/wVVbT/9 - 这有帮助吗?
  • 我需要在鼠标停止移动时执行该行...所以您刚刚发布的更新代码不是我想要的
  • @RyanSaxe - 好的,这个怎么样:jsfiddle.net/wVVbT/13(注意:归功于 adeneo,我刚刚添加和删除了一些代码)

标签: javascript jquery mouseevent


【解决方案1】:

您添加一个在不活动一秒后触发的超时,如果鼠标在 1 秒内移动则清除超时等:

var timer;
$(document).on('mousemove', function(e){
   clearTimeout(timer);

   timer = setTimeout(function() {
       $('.fall').fadeOut('slow', function() {
           $(this).remove();
       });
   }, 1000);
});

FIDDLE

编辑:

这就是我的做法

FIDDLE

【讨论】:

  • 目标是让它们在停止时淡出。这不会那样做,它只会让它停止绘图。然后你就不能重新开始了……
  • @RyanSaxe - 但他们不是已经淡出了吗?无论如何,编辑答案,找出鼠标停止一秒钟等的相同原理。
  • @adeneo - 我认为他们想要这样的东西:jsfiddle.net/wVVbT/13 - 他们需要做的就是删除原始函数中的几行代码。
  • @adeneo +1 很棒的方法!只是一个注释。为了获得最佳实践,您上面和小提琴中的代码可能应该使用 clearTimeout,而不是 clearInterval,因为您正在设置超时。见stackoverflow.com/questions/9913719/…
【解决方案2】:

这是您需要的吗? jsFiddle

lastTimeMouseMoved = new Date().getTime();
var t = setTimeout(function() {
  var currentTime = new Date().getTime();
  if (currentTime - lastTimeMouseMoved > 1000) {
    $('.fall').fadeOut('slow');
    // $('.fall').remove();
  }
}, 1000)

【讨论】:

  • 这几乎是完美的!!这正是重点......但它不会淡出,它只是被移除
  • 只是评论 // $('.fall').remove();会做的
  • @Down voter - 如果您对答案投反对票,请随时描述原因
猜你喜欢
  • 1970-01-01
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-13
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多