2011-06-20 56 views
16

用普通的JS/JQuery跟蹤鼠標速度的最佳方式是什麼?我想跟蹤用戶在各個方向(上/下/左/右)移動鼠標的速度。用JS跟蹤鼠標速度

回答

15

Sparklines has a nifty example跟蹤鼠標移動並繪製圖形。他們的代碼可從他們的網站獲得,從315行開始。

簡單而有效。

下面是代碼:

var mrefreshinterval = 500; // update display every 500ms 
var lastmousex=-1; 
var lastmousey=-1; 
var lastmousetime; 
var mousetravel = 0; 
$('html').mousemove(function(e) { 
    var mousex = e.pageX; 
    var mousey = e.pageY; 
    if (lastmousex > -1) 
     mousetravel += Math.max(Math.abs(mousex-lastmousex), Math.abs(mousey-lastmousey)); 
    lastmousex = mousex; 
    lastmousey = mousey; 
}); 
+0

中顯示以下是完整的代碼片段 - https://gist.github.com/ripper234/5757309 – ripper234

+0

此解決方案僅跟蹤鼠標距離嗎?爲什麼距離是x和y座標的差值的最大值,而不是差值的平方和?並且'mrefreshinterval'是「預定義」屬性?我不明白你是如何使用它的。謝謝。 – Dambo

7

相同的方式,獲得速度爲別的:

speed = distance/time 

acceleration = speed/time 

及用途:

$(document).mousemove(function(e){ 
    var xcoord = e.pageX; 
    var ycoord = e.pageY; 
}); 

要獲得鼠標座標,只要鼠標移動。

+3

是的,但您需要至少兩次鼠標移動以獲得正確的時間。假設你將鼠標移動到[5,5],然後凍結10秒。然後你在瞬間快速移動到[10,5],10秒內輸出將爲10個像素,因爲當你最後一次記錄時間戳時[5,5]是。我知道對於鼠標移動,第一次實際移動通常並不重要,因爲您觸發的次數更多,但我也嘗試過這種移動方式,如果您的滑動速度非常快,那麼您可能只需要一次移動即可使用。 – treznik

+0

我同意@treznik,從你的代碼中不清楚你是如何從變量「time」中獲得值的。 – S4M

+0

請在jsfiddle @connor – ShibinRagh

6
var timestamp = null; 
var lastMouseX = null; 
var lastMouseY = null; 

document.body.addEventListener("mousemove", function(e) { 
    if (timestamp === null) { 
     timestamp = Date.now(); 
     lastMouseX = e.screenX; 
     lastMouseY = e.screenY; 
     return; 
    } 

    var now = Date.now(); 
    var dt = now - timestamp; 
    var dx = e.screenX - lastMouseX; 
    var dy = e.screenY - lastMouseY; 
    var speedX = Math.round(dx/dt * 100); 
    var speedY = Math.round(dy/dt * 100); 

    timestamp = now; 
    lastMouseX = e.screenX; 
    lastMouseY = e.screenY; 
}); 
+2

請在您的代碼中添加一些說明。爲什麼你認爲這是一個答案?以前的答案是錯誤的還是低效的?或者,也許你想對問題展示不同的方法?只發布一段代碼不是答案。 – Artemix

+0

這是更正確的,而不是使用間隔。在每次迭代中(除了第一次)我們都會知道速度。當我們使用間隔時,我們有平均速度(在這個間隔內)。 – verybadbug

2

這是對付你可以開始跟蹤,暫停,然後飛快的移動你的手指或鼠標的事實的方法(假設上的觸摸突然一抖屏幕)。

var time = 200 
var tracker = setInterval(function(){ 
    historicTouchX = touchX; 
}, time); 

document.addEventListener("touchmove", function(){ 
    speed = (historicTouchX - touchX)/time; 
    console.log(Math.abs(speed)); 
}, false); 

我在這個例子中只使用了touchX。我們的想法是每200毫秒拍攝x位置的快照,然後從當前位置開始拍攝,然後除以200(速度=距離/時間)。這將保持速度的全新更新。時間是毫秒,輸出將是每200毫秒行進的像素數。