当鼠标下的元素移动时,如何阻止mousemove()执行? [英] How to stop mousemove() from executing when the element under the mouse moves?
问题描述
我正在使用来自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上时,c $ c>,在
#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屋!