[英]jQuery: mousemove event - left, right within element
我想得到一個div的鼠標坐標,像這樣:
$("#box").mousemove(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
document.getElementById("coords").innerHTML = x + ", " + y; });
但我也希望能夠判斷光標是向左還是向右移動; 我知道我只需將當前鼠標位置與之前的鼠標位置進行比較,但我不知道在這種情況下如何做到這一點。
任何幫助贊賞。 謝謝
獲取鼠標位置的jquery代碼如下
jQuery(document).ready(function(){
$(document).mousemove(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
})
顯然你必須有一個名為“狀態”的div
<div id="status">0, 0</div>
要檢查光標是向右移動還是向右移動,您必須存儲先前的位置,然后將其與新的位置進行比較。
在這里,我給你寫了完整的例子:
_ 編輯:
如果你需要在div中獲得坐標,你還需要知道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/
您可以使用以下解決方案:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.