如何确定鼠标移动事件的方向

How to determine the direction on onmousemove event?

本文关键字:方向 事件 移动 何确定 鼠标      更新时间:2023-09-26

例如,在某些情况下,我想在鼠标按下时取消onmousemove事件。是否可以确定onmousemove事件的方向?jQ 或 JS 是可以的。

我有拖放元素。用户向上拖动。例如,如果元素的底部到达文档中的某个位置(即 500px从文档顶部开始(onmousemove停止。如果用户尝试再次向上拖动元素,则函数将不会启动。此元素只能向下拖动。所以我认为通过抓住mousemove事件的方向很容易做到这一点。但似乎没有这种标准属性。

您可以保存上一个mousemove事件的位置以与当前位置进行比较:

//setup a variable to store our last position
var last_position = {},
$output       = $('#output');
//note that `.on()` is new in jQuery 1.7 and is the same as `.bind()` in this case
$(document).on('mousemove', function (event) {
    //check to make sure there is data to compare against
    if (typeof(last_position.x) != 'undefined') {
        //get the change from last position to this position
        var deltaX = last_position.x - event.clientX,
            deltaY = last_position.y - event.clientY;
        //check which direction had the highest amplitude and then figure out direction by checking if the value is greater or less than zero
        if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX > 0) {
            //left
        } else if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX < 0) {
            //right
        } else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY > 0) {
            //up
        } else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY < 0) {
            //down
        }
    }
    //set the new last position to the current for next time
    last_position = {
        x : event.clientX,
        y : event.clientY
    };
});

这是一个演示:http://jsfiddle.net/Dv29e/

更新

您还可以限制mousemove事件,以更大致地了解鼠标的移动位置:

var last_position = {},
    $output       = $('#output'),
    mousemove_ok  = true,
    mouse_timer   = setInterval(function () {
        mousemove_ok = true;
    }, 500);
$(document).on('mousemove', function (event) {
    if (mousemove_ok) {
        mousemove_ok = false;
        ...
    }
});

只有在以下情况下,这将检查光标的位置与其过去的位置:

  1. 最后一个位置存在。
  2. mousemove_ok变量设置为 true每半秒完成一次。

这是一个受限制的演示:http://jsfiddle.net/Dv29e/4/

有一些标准属性显示与上一个鼠标移动事件相关的增量:

document.addEventListener('mousemove', function (event) {
  directionX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
  directionY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
});

就像文档中所说的那样:

MouseEvent.movementX 只读属性提供鼠标指针的 X 坐标在该事件和上一个鼠标移动事件之间的偏移。

event.movementX是与前一个位置X的px之差,例如100表示右移动100 px,-100表示左移动等,0表示无移动。