detect mouse direction

蓝咒 提交于 2019-11-30 08:44:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!