检测鼠标方向

时间:2011-12-09 18:46:32

标签: javascript jquery mouseevent direction

我正在尝试使用此代码来检测鼠标方向是上升还是下降:

<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');
    }

});

然而,这段代码不起作用,我期待。控制台日志始终显示“从顶部”

有什么想法吗?

demo

6 个答案:

答案 0 :(得分:10)

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;

});

答案 1 :(得分:4)

您在比较之前设置my = e.pageY,这意味着比较将始终相等(因此为假。)

尝试这样

var mY = 0;
$('body').mousemove(function(e) {

    if (e.pageY < mY) {
        console.log('From Bottom');

    } else {
        console.log('From Top');
    }
    mY = e.pageY;

});

答案 2 :(得分:1)

e.pageY始终等于mY,因为您在mY声明之前将e.pageY设置为if

答案 3 :(得分:0)

您需要在确定方向之后设置mY值(之前您先设置它 - 因此始终会收到特定结果)

<强>代码:

//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

答案 4 :(得分:0)

如果使用if / else,它将始终输出'Going Down',即使e.pageY == mY。

改为使用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;

});

刚刚从macek复制了代码,并用'if(...)'btw

替换了'else'

答案 5 :(得分:0)

最简单的方法。这样您就可以检测方向变化:

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');
    }

 });