如何计算keyup

时间:2016-12-16 07:08:57

标签: javascript jquery

这是代码,但它不起作用,哪里出错。

<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) }); });

很高兴为你们提供帮助

5 个答案:

答案 0 :(得分:2)

您可以使用类似于会话变量的JavaScript存储:

<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>

答案 1 :(得分: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 !!
});

答案 2 :(得分:0)

计算keydown和keyup之间的时间:

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">

答案 3 :(得分: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;
   });
 });

答案 4 :(得分: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>