javascript 检测鼠标方向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8450199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
detect mouse direction
提问by daniel__
I am trying this code to detect if the mouse direction is going up or down:
我正在尝试使用此代码来检测鼠标方向是向上还是向下:
<html>
<head></head>
<body>
<div style="width: 500px; height: 500px; background: red;"></div>
</body>
</html>
var mY = 0;
$('body').mousemove(function(e) {
mY = e.pageY;
if (e.pageY < mY) {
console.log('From Bottom');
return;
} else {
console.log('From Top');
}
});
However this code doesn't work was i expect. Console log always show "from top"
但是,此代码不起作用是我所期望的。控制台日志总是显示“从顶部”
Any idea ?
任何的想法 ?
回答by ma?ek
var mY = 0;
$('body').mousemove(function(e) {
// moving upward
if (e.pageY < mY) {
console.log('From Bottom');
// moving downward
} else {
console.log('From Top');
}
// set new mY after doing test above
mY = e.pageY;
});
回答by Karmic Coder
You are setting my = e.pageY
before comparing it, which means the comparison will always be equal (and therefore false.)
您my = e.pageY
在比较之前进行设置,这意味着比较将始终相等(因此为假。)
try it like this
像这样试试
var mY = 0;
$('body').mousemove(function(e) {
if (e.pageY < mY) {
console.log('From Bottom');
} else {
console.log('From Top');
}
mY = e.pageY;
});
回答by schnozzinkobenstein
e.pageY
is always equal to mY
because you set mY
to e.pageY
just before the if
statement.
e.pageY
始终等于,mY
因为您在语句之前设置mY
为。e.pageY
if
回答by Rion Williams
You needed to set your mY
value after determining the direction (previously you were setting it prior - thus would always receive a specific result)
您需要mY
在确定方向后设置您的值(以前您是事先设置的 - 因此总是会收到特定的结果)
Code:
代码:
//Values starts at middle of page
var mY = $('window').height()/2;
//Compares position to mY and Outputs result to console
$('body').mousemove(function(e) {
if (e.pageY < mY) {
console.log('Going Up');
}
else {
console.log('Going Down');
}
mY = e.pageY;
});
回答by Norman
if you use if/else it will always output 'Going Down', even though e.pageY == mY.
如果您使用 if/else,它将始终输出“Going Down”,即使 e.pageY == mY。
Use 2 if-statements instead!
改用 2 个 if 语句!
var mY = 0;
$('body').mousemove(function(e) {
// moving upward
if (e.pageY < mY) {
console.log('From Bottom');
// moving downward
}
if (e.pageY > mY) {
console.log('From Top');
}
// set new mY after doing test above
mY = e.pageY;
});
just copied the code from macek and replaced the 'else' with an 'if(...)' btw
刚刚从 macek 复制了代码,并用 'if(...)' 替换了 'else' 顺便说一句
回答by Paulo Rodrigues
The easiest way to do it. This way you can detect direction changes:
最简单的方法。通过这种方式,您可以检测方向变化:
var tempMouseY=0;
$('body')
.mousemove(function(e) {
moveY = -(tempMouseY-e.pageY);
tempMouseY = e.pageY;
if (moveY<0) {
console.log('From Bottom');
} else {
console.log('From Top');
}
});