2016-12-16 62 views
0

這是代碼,但它不工作,哪裏出錯。如何計算keydown到keyup的時間

<input type="text" name ="name" place=""> <button disabled="disabled">click</button> <script> $(function(){ var i = 0; $('input').keydown(function(event) { i++; var temp = i; setTimeout(function(){ var rate = (i-temp); console.log(rate); if(rate--){ $('button').attr('disabled',true); }else{ $('button').attr('disabled',false); } },1000) }); });

THX這麼多,你們幫

+0

你試過嗎? – Mairaj

+0

是的,但事情是我想知道用戶按鍵盤的速度, – WUSO01

回答

0

計算時間:

timebetween = 0; 
 
var count = null; 
 
$("input").keydown(function(){ 
 
    timebetween = 0; 
 
    count = setInterval(function(){ 
 
     timebetween++; 
 
    }, 1); 
 
}); 
 

 
$("input").keyup(function(){ 
 
    clearInterval(count); 
 
    $("body").append("<br>Time between keydown and keyup is "+timebetween+"ms"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text">

1

在jQuery中,你可以使用下面的代碼:

的KeyDown:

$("input").keydown(function(){ // when user push the key 
// do something !! 
}); 

KEYUP:

$("input").keyup(function(){ // when user is not pushing key enymore 
// do something !! 
}); 
+0

OKay,Thx的兄弟,但事情是我想知道用戶按鍵盤的速度, – WUSO01

+0

什麼是鍵盤速率?你的意思是鍵盤上的按鍵? –

+0

換句話說,如何計算keydown到keyup的時間 – WUSO01

2

您可以使用JavaScript存儲這類似於會話變量:KeyDown和KEYUP之間

<script> 
    window.onload = function() { 
     document.onkeydown=(function (event) { 
      if (localStorage["Count"] == null) { 
       localStorage["Count"] = 0; 
      } 
      else { 
       localStorage["Count"]++; 
      } 

      alert("The count is: " + localStorage["Count"]); 
     }); 
    } 
</script> 
+0

哦!我的意思是如何計算keyyd的時間keydown – WUSO01

0

你可以試試這個,它會給你時間以毫秒爲單位。

$(document).ready(function(){ 
    var startTime = false, endTime; 
    $(window).keypress(function(){ 
    if(!startTime){ 
     startTime = $.now(); 
    } 
    }); 

    $(window).keyup(function(){ 
     endTime = $.now(); 
     var keyPressedTime = (endTime - startTime); 
     console.info('keyyyUpppp', keyPressedTime) 
     startTime = false; 
    }); 
}); 
0

您可以使用此:

<!DOCTYPE HTML> 
 

 
<html> 
 

 
<head> 
 
    <title>Js Project</title> 
 
</head> 
 

 
<body> 
 

 
<input type="text" id="txt" /> 
 

 
<div id="label"></div> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<script type="text/javascript"> 
 

 
var time = 0; // pressing time 
 
var pressed = 0; // key is pushed or not ? 
 

 
var timer = setInterval(calculate, 10); // calculate time 
 

 
$("#txt").keydown(function(){ 
 
pressed = 1; 
 
}); 
 

 
$("#txt").keyup(function(){ 
 
pressed = 0; 
 
$("#label").html("Pressing Time : "+time+" ms"); 
 
time = 0 
 
}); 
 

 
function calculate() { // increase pressing time if key is pressed !! 
 
    if (pressed == 1) { 
 
     time += 1; 
 
    } 
 
} 
 

 
</script> 
 

 
</body> 
 

 
</html>