当鼠标下的元素移动时,如何阻止mousemove()执行? [英] How to stop mousemove() from executing when the element under the mouse moves?

查看:516
本文介绍了当鼠标下的元素移动时,如何阻止mousemove()执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用来自SO用户的这段代码:

I'm using this piece of code from a fellow SO user:

   $("#rightSubMenu").mousemove(function(e){
      console.log('executed');
      var h = $('#rightSubMenuScroller').height()+13;
      var offset = $($(this)).offset();
      var position = (e.pageY-offset.top)/$(this).height();
      if(position<0.33) {
         $(this).stop().animate({ scrollTop: 0 }, 1000);
      }
      else if(position>0.66) {
         $(this).stop().animate({ scrollTop: h }, 2000);
      }
      else
      {
         $(this).stop();
      }
   });

它的作用基本上是它移动 #rightSubMenuScroller ,在 #rightSubMenu 里面。问题在于,每移动一个像素,它会再次执行整个函数,从而产生滞后动画。

What it does, basically, is that it moves #rightSubMenuScroller, which is inside #rightSubMenu, whenever you hover over rightSubMenu. The problem is that with every pixel moved, it executes the whole function again resulting in a laggy animation.

当我激活滚动并将鼠标移离元素时,动画很好。

When I activate the scrolling and move the mouse away from the element, the animation is nice.

我需要修复代码,以免它滞后。有什么想法吗?

I need to fix the code so that it doesn't lag. Any ideas how?

推荐答案

你应该添加 event.stopPropagation()在此事件调用结束时。

You should add event.stopPropagation() at the end of this event call.

$("#rightSubMenu").mousemove(function(e){
  // You code...
  e.stopPropagation();
});

这将阻止事件冒泡DOM树。

This will prevent the event bubbling up the DOM tree.

或者,根据您的DOM结构,尝试 event.stopImmediatePropagation()保持所有其他事件处理程序的执行。

Alternatively and depending on your DOM structure, try event.stopImmediatePropagation() which keeps all other event handlers executing.

这篇关于当鼠标下的元素移动时,如何阻止mousemove()执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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