2012-12-27 44 views
4

我想一个div的鼠标COORDS,像这样:jQuery的:mousemove事件 - 左,右内元素

$("#box").mousemove(function(e){ 
var x = e.pageX - this.offsetLeft; 
var y = e.pageY - this.offsetTop; 

document.getElementById("coords").innerHTML = x + ", " + y; }); 

但我也希望能够告诉我们,如果游标移到左或对;我知道我只需要将当前鼠标位置与前一个鼠标位置进行比较,但在这种情况下我不知道如何操作。

任何帮助表示赞赏。谢谢

+0

参见HTTP://小号tackoverflow.com/a/2725963/287948 –

回答

13

jQuery代码来获得鼠标的位置下面

jQuery(document).ready(function(){ 

    $(document).mousemove(function(e){ 
     $('#status').html(e.pageX +', '+ e.pageY); 
    }); 
}) 

显然,你必须叫格“状态”

<div id="status">0, 0</div> 

要检查是否光标移动到左边或右边你是对的,你必须存储以前的位置,然后与新的比较。

在这里,我给你写了完整的示例:

http://jsfiddle.net/cB9Wq/

_编辑:

如果你需要让你也需要知道的位置的分区内COORDS在div:

$(".div_container").mousemove(function(e){ 
     var relativeXPosition = (e.pageX - this.offsetLeft); //offset -> method allows you to retrieve the current position of an element 'relative' to the document 
     var relativeYPosition = (e.pageY - this.offsetTop); 
     $("#header").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>") 
    }).mouseout(function(){ 
     $("#header").html("<p>Move mouse on the below blue div container! :)</p>") 
    }); 

要检查鼠标变为向左或向右,我用这个sintax:

xPrev<e.pageX ? $('#lr').html("right") : $('#lr').html("left"); 
xPrev=e.pageX; 

注:这是等同于:

if(xPrev<e.pageX) { 
    $('#lr').html("right"); 
} 
else { 
    $('#lr').html("left"); 
} 
xPrev=e.pageX; 

在这里,你有工作示例:http://jsfiddle.net/cB9Wq/2/

+1

我可能说错了;我正在使用相对鼠标位置#box,所以当光标在#box的左上角时,鼠标位置将始终为0,0 - 无论#box位置如何 – user1207524

+0

我发布了您的工作示例, DIV。 ;) – Danilo

1

您可以采用如下方案:

var plotSliderLastPostion = 0; //Placed outside the scope of function (fxp like private member) 

slider.addEventListener(EVENT.MOUSE_MOVE, function(e){ 
var relativePlotBoxPositionX = e.clientX - rect.left; 
//CHECK THAT CURSOR IS MOVING RIGHT OR LEFT 
        if(relativePlotBoxPositionX > plotSliderLastPostion) { 
         console.log("right"); 
         plotSliderLastPostion = relativePlotBoxPositionX; 
        } 
        else { 
         console.log("left"); 
         plotSliderLastPostion = relativePlotBoxPositionX; 
        } 
    }, true);