检测鼠标的真实方向

时间:2019-01-03 22:15:03

标签: javascript mouseevent mouse mousemove

我的目标是在mouseup事件触发之前检测鼠标的最后移动方向。

为避免验证较小的非自愿移动(例如:我将鼠标向右移动100px,然后停下来,但非自愿地向左移动2px),只有在鼠标指针达到最小安全距离后才能确认方向(间隙)从其反转方向的最后一点开始。

这是我的实现的简化:

var direction = "",
oldx = 0,
invert = 0,
gap = 10,
move = "",
mousemovemethod = function (e) {

    if (e.pageX < oldx) {
        if(direction == "right") invert = e.pageX;
        direction = "left";
        if(e.pageX < invert - gap) move = "left";
    } else if (e.pageX > oldx) {
        if(direction == "left") invert = e.pageX;
        direction = "right"
        if(e.pageX > invert + gap) move = "right";
    }

    document.body.innerHTML = "moving " + direction + ", last inversion point: " + invert + ", Validated movement: " + move;

    oldx = e.pageX;

}

document.addEventListener('mousemove', mousemovemethod);

这是fiddle

该代码有效,但在我看来似乎很冗长和不清楚。我在这种实现上一直很穷,我想知道是否有人知道一种更优雅的方式来处理这种机制。

欢迎任何建议。

1 个答案:

答案 0 :(得分:0)

function smooth(){
    var direction="",
    oldx = 0,
    noise=10,
    dir=0;
    mousemove=function(e){
       dir=oldx-e.pageX;
       if(Math.abs(dir)> noise){
          (dir <=0 )?direction="right":direction="left";
          oldx=e.pageX;
       }
       document.body.innerHTML = "moving " + direction;
   };
   document.addEventListener('mousemove', mousemove);
}

怎么样?