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。
答案 0 :(得分:7)
坚持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;
}
答案 1 :(得分:1)
此代码将为您提供方向&#39; &#39; X&#39;和&#39; Y&#39;在directionX和方向Y变量 以及&#39; X&#39;和&#39; Y&#39;轴。
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);
答案 2 :(得分:0)
鼠标移动-向左,向右,向上,向下-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);
答案 3 :(得分:0)
您无需跟踪旧职位。
e.clientX - window.innerWidth/2 > 0 ? 'right' : 'left'
e.clientY - window.innerHeight/2 > 0 ? 'bottom' : 'top'
答案 4 :(得分:0)
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";
}