如何检测Mousedown + Mousemove左右方向

时间:2015-10-03 07:11:52

标签: javascript jquery

请您看看这个演示,让我知道如何检测鼠标是向左还是向右?

 $('.container').mousedown(function(){
    $(this).mousemove(function(){
      //if Moves Left { console.log("Moving Left"); }
      //if Moves Right {  console.log("Moving Right"); }
    });
});     
  $('.container').mouseup(function(){
    $(this).unbind("mousemove");
});      
.container {
    height:200px;
    width:200px;
    background-color:#1abc9c;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

3 个答案:

答案 0 :(得分:1)

绝对是众多解决方案中的一个:

$('.container').mousedown(function(e1){
    var mx = e1.pageX;//register the mouse down position

    $(this).mousemove(function(e2){

        if (e2.pageX > mx){ //right w.r.t mouse down position
            console.log("Moved Right");
        } else {
            console.log("Moved Left")
        }
    });
});     
  $('.container').mouseup(function(){
    $(this).unbind("mousemove");
});      

工作代码here

答案 1 :(得分:0)

&#13;
&#13;
.container {
    height:200px;
    width:200px;
    background-color:#1abc9c;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
&#13;
!contents -R2 -g -p -f -h

!path lib/*.jar

|import |
|dbfit.SqlServerTest|

!|dbfit.SqlServerTest|

!|Connect|SUKHI-PC\SQLEXPRESS|SUKHI-PC\XXX|XXX|XXX|
&#13;
&#13;
&#13;

答案 2 :(得分:0)

对,这很容易,只需在脚本标记中添加此代码并在控制台上查看即可。

var bodyElement = document.querySelector("body");
bodyElement.addEventListener("mousemove", getMouseDirection, false);
 
var xDirection = "";
var yDirection = "";
 
var oldX = 0;
var oldY = 0;
 
function getMouseDirection(e) {
    //deal with the horizontal case
    if (oldX < e.pageX) {
        xDirection = "right";
    } else {
        xDirection = "left";
    }
 
    //deal with the vertical case
    if (oldY < e.pageY) {
        yDirection = "down";
    } else {
        yDirection = "up";
    }
 
    oldX = e.pageX;
    oldY = e.pageY;
 
    console.log(xDirection + " " + yDirection);
}