检测鼠标方向 - JavaScript

Posted

技术标签:

【中文标题】检测鼠标方向 - JavaScript【英文标题】:Detect mouse direction - JavaScript 【发布时间】:2014-08-09 06:35:13 【问题描述】:
var direction = ""
var mousemovemethod = function (e) 
    var oldx = 0;
    if (e.movementX < oldx) 
        direction = "left"
     else if (e.movementX > oldx) 
        direction = "right"
    
    oldx = e.pageX;

这就是我检测鼠标方向的方法,它工作得很好,但它只适用于 Chrome,我如何使它与其他浏览器(Firefox、Opera 和至少 ie8+ 或 ie9+)兼容。 请不要使用 jQuery。

【问题讨论】:

【参考方案1】:
let direction = "";
if (e.movementY > 0 && e.movementX == 0) 
    direction = "down";
   else if (e.movementY < 0 && e.movementX == 0) 
    direction = "up";
   else if (e.movementX > 0 && e.movementY == 0) 
    direction = "right";
   else if (e.movementX < 0 && e.movementY == 0) 
    direction = "left";
  

【讨论】:

【参考方案2】:

您不需要跟踪旧位置。

   e.clientX - window.innerWidth/2 > 0 ? 'right' : 'left'
   e.clientY - window.innerHeight/2 > 0 ? 'bottom' : 'top'

【讨论】:

【参考方案3】:

鼠标移动 - 向左、向右、向上、向下 - javascript FIDDLE

var direction = "";
    var oldx = 0;
    var oldy = 0;
    mousemovemethod = function (e) 
    
 if (e.pageX > oldx && e.pageY == oldy) 
                direction="East";
            
            else if (e.pageX == oldx && e.pageY > oldy) 
                direction="South";
            
            else if (e.pageX == oldx && e.pageY < oldy) 
                direction="North";
            
            else if (e.pageX < oldx && e.pageY == oldy) 
                direction="West";
            
        
        document.body.innerhtml = direction;
        
        oldx = e.pageX;
         oldy = e.pageY;
        


document.addEventListener('mousemove', mousemovemethod);

【讨论】:

【参考方案4】:

此代码将为您提供 'X' 和 'Y' 在 directionX 和方向 Y 变量中的 'direction' 以及 'X' 和 'Y' 轴行进的距离。

 let oldX = 0, oldY = 0;

 function captureMouseMove($event)
      let directionX = 0, directionY = 0, diffX = 0, diffY = 0;
      if ($event.pageX < oldX) 
          directionX = "left"
          diffX = oldX - $event.pageX;
       else if ($event.pageX > oldX) 
          directionX = "right"
          diffX = $event.pageX - oldX;
      

      if ($event.pageY < oldY) 
          directionY = "top"
          diffY = oldY - $event.pageY;
       else if ($event.pageY > oldY) 
          directionY = "bottom";
          diffY = $event.pageY - oldY;
      

      oldX = $event.pageX;
      oldY = $event.pageY;
  

  window.addEventListener('mousemove', captureMouseMove);

【讨论】:

【参考方案5】:

坚持pageX,在更高的范围内定义oldx,否则永远为零

var direction = "",
    oldx = 0,
    mousemovemethod = function (e) 

        if (e.pageX < oldx) 
            direction = "left"
         else if (e.pageX > oldx) 
            direction = "right"
        

        oldx = e.pageX;


FIDDLE

【讨论】:

非常感谢您解决了 oldx 问题我想知道为什么它不适用于 pageX...

以上是关于检测鼠标方向 - JavaScript的主要内容,如果未能解决你的问题,请参考以下文章

检测鼠标方向

ActionScript 3 检测方向鼠标正在移动

04射线的检测Trace01

如果单独设置mac鼠标滚轮方向?

鼠标怎样制作游戏方向盘用啥驱动

ubuntu17.10鼠标滚轮方向反了,请问咋解决