13

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

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

4

3 回答 3

28

您可以保存最后一个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/

于 2012-01-28T18:21:25.847 回答
7

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

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

就像文档中所说的:

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

于 2016-07-31T07:48:15.477 回答
0

event.movementX 是与前一个 positionX 的 px 差异,例如 100 表示向右移动 100 px,-100 表示向左移动等,0 表示没有移动。

于 2017-08-29T07:08:45.367 回答