如何确定onmousemove事件的方向?

时间:2012-01-28 18:12:12

标签: javascript jquery mouseevent onmousemove

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

我有拖拽元素。用户拖动元素。例如,如果元素的底部到达文档中的某个位置(即文档顶部的500px),onmousemove就会停止。如果用户将尝试再次向上拖动元素,则该功能将无法启动。只能向下拖动此元素。因此我认为通过捕捉mousemove事件的方向来实现它会非常容易。但似乎没有这种标准属性。

3 个答案:

答案 0 :(得分:23)

您可以保存上一个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,每半秒完成一次。
  3. 这是一个受限制的演示:http://jsfiddle.net/Dv29e/4/

答案 1 :(得分:7)

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

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

documentation中所述:

  

MouseEvent.movementX只读属性提供鼠标指针在该事件与之前的mousemove事件之间的X坐标的移位。

答案 2 :(得分:0)

event.movementX是px与之前positionX的差异,例如100表示​​正确移动100 px,-100表示​​左移动等,0表示没有移动。