2014-07-09 55 views
1

我正在監聽鍵和鼠標輸入10秒鐘,並通過將對象推送到包含事件發生時間的數組以及mouseX和Y來「記錄」活動鼠標輸入以及哪個鍵被按下。最終,我想通過一些動畫功能運行這個「歷史記錄」,並「重放」用戶輸入的內容。捕獲單鍵輸入事件Jquery

一個奇怪的事情正在發生,我會按一次按鍵,並期望在最後,keyCapture是一個對象的數組。相反,我變得像100多個對象,我不知道爲什麼。他們中的許多人都是重複的,甚至時間是相同的。

function captureInput() { 

mouseCapture = []; 
keyCapture = []; 

$(document).on('mousemove.capture', function(e) { 
    var time = new Date().getTime(); 
    mouseCapture.push({ 
    x: e.pageX, 
    y: e.pageY, 
    t: time 
    }); 

    $(document).on('keyup.capture', function(e) { 
    var time = new Date().getTime(); 
    keyCapture.push({ 
     key: e.which, 
     t: time 
    }) 
    }); 

}); 

setTimeout(function() { 
    $(document).off('.capture'); 
    console.log(mouseCapture); 
    console.log(keyCapture); 
}, 10000); 

} 

我該如何更改我的代碼,因此我只爲每個鍵盤事件推送一個鍵控對象?

回答

4

您正在鼠標事件中註冊您的按鍵(每次都是,一遍又一遍)!將它移到該函數調用之外:

function captureInput() { 

    mouseCapture = []; 
    keyCapture = []; 

    $(document).on('mousemove.capture', function (e) { 
     var time = new Date().getTime(); 
     mouseCapture.push({ 
      x: e.pageX, 
      y: e.pageY, 
      t: time 
     }); 

    }); 

    $(document).on('keyup.capture', function (e) { 
     var time = new Date().getTime(); 
     keyCapture.push({ 
      key: e.which, 
      t: time 
     }) 
    }); 

    setTimeout(function() { 
     $(document).off('.capture'); 
     console.log(mouseCapture); 
     console.log(keyCapture); 
    }, 10000); 

} 

我使用JSFiddle.net上的TidyUp按鈕格式化代碼。問題變得很明顯,當縮進是正確的:)

+0

是的,你捕捉每一隻鼠標.. – webkit

+0

非常感謝!問題解決了。 –

2

我注意到這個有語法高亮

$(document).on('mousemove.capture', function(e) { // starts 
    var time = new Date().getTime(); 
    mouseCapture.push({ 
    x: e.pageX, 
    y: e.pageY, 
    t: time 
    }); 

    // }); should end here 

    $(document).on('keyup.capture', function(e) { 
    var time = new Date().getTime(); 
    keyCapture.push({ 
     key: e.which, 
     t: time 
    }) 
    }); 

}); // ends 

您的問題似乎是,每次移動,你會不斷創造監聽事件,這樣的時候,你按一個鍵所有這些將鼠標運行導致很多對象