问题
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 ?
demo
回答1:
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;
});
回答2:
You are setting my = e.pageY
before comparing it, which means the comparison will always be equal (and therefore false.)
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;
});
回答3:
e.pageY
is always equal to mY
because you set mY
to e.pageY
just before the if
statement.
回答4:
You needed to set your mY
value after determining the direction (previously you were setting it prior - thus would always receive a specific result)
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;
});
Working Example
回答5:
if you use if/else it will always output 'Going Down', even though e.pageY == mY.
Use 2 if-statements instead!
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
回答6:
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');
}
});
来源:https://stackoverflow.com/questions/8450199/detect-mouse-direction