如何确定onmousemove事件的方向?

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

我有拖拉元素。 用户拖动元素。 例如,如果元素的底部到达文档中的某个位置(即距文档顶部500px ),则onmousemove停止。 如果用户将尝试再次向上拖动元素,则该function将无法启动。 只能向下拖动此元素。 因此我认为通过捕捉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只读属性提供该事件与上一个mousemove事件之间鼠标指针的X坐标的移位。

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