【问题标题】:How to stop mousemove() from executing when the element under the mouse moves?当鼠标下的元素移动时,如何阻止 mousemove() 执行?
【发布时间】:2012-01-15 20:33:47
【问题描述】:

我正在使用来自 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();
      }
   });

它的作用基本上是移动#rightSubMenuScroller,它位于#rightSubMenu 内,每当您将鼠标悬停在rightSubMenu 上时。问题在于,随着每个像素的移动,它会再次执行整个函数,从而导致动画滞后。

当我激活滚动并将鼠标从元素上移开时,动画效果很好。

我需要修复代码以使其不会滞后。有什么想法吗?

【问题讨论】:

    标签: jquery


    【解决方案1】:

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

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

    这将防止事件在 DOM 树中冒泡。

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

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-24
        • 1970-01-01
        • 2012-12-31
        • 1970-01-01
        • 2014-09-18
        相关资源
        最近更新 更多