我正在使用 SO 用户的这段代码:
$("#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();
}
});
基本上,它的作用是,每当您将鼠标悬停在 rightSubMenu 上时,它就会移动 #rightSubMenuScroller
(位于 #rightSubMenu
内)。问题是,每移动一个像素,它就会再次执行整个函数,从而导致动画滞后。
当我激活滚动并将鼠标移离元素时,动画效果很好。
我需要修复代码,使其不会滞后。有什么想法吗?
最佳答案
您应该添加event.stopPropagation()在本次事件通话结束时。
$("#rightSubMenu").mousemove(function(e){
// You code...
e.stopPropagation();
});
这将防止事件在 DOM 树中冒泡。
或者,根据您的 DOM 结构,尝试 event.stopImmediatePropagation()它使所有其他事件处理程序保持执行。
关于jquery - 当鼠标下方的元素移动时,如何阻止 mousemove() 执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8873153/