simple javascript keystroke count

无人久伴 提交于 2019-12-07 23:00:43

http://jsfiddle.net/kBJGM/

HTML:

<input type="text" class="nopaste"/>
<input type="text" id="countstroke"/>
<span id="count"></span>​

Javascript:

var strokeCount = 0;

$(function(){

    $(".nopaste").bind("copy paste", function(e){
        e.preventDefault();
    });

    $("#countstroke").keyup(function(){
        $("#count").text("Count: " + (++strokeCount));
    });
});​

If you want to take it a step further, you can enforce that only the L and R keys are registered (http://jsfiddle.net/kBJGM/5/):

$("#restrictivecount").keypress(function(e){
    var seq = rstrokeCount % 2;
    var allow = true;
    switch(e.keyCode){
        case 76:
        case 108: // L or l
            if (seq == 1) allow = false;
        break;
        case 82:
        case 114: // R or r
            if (seq == 0) allow = false;
        break;               
        default:
            allow = false;
        break;               
    }

    if (allow)
        $("#rcount").text("Count: " + (++rstrokeCount));
    else
        e.preventDefault();
});
var keyPressCount = 0;

$(document).on("keydown",function(){
   keyPressCount++;
});

check out this fiddle

Yauhen Vasileusky
count=0;

$(document).bind('keydown', function(event){
    var keyCode = event.keyCode;
    switch(keyCode){
        case 39:
            alert('Right arrow was pressed');
            count++;
            break;
        case 37:
            alert('Left arrow was pressed');
            count++;
            break;
    }
});

You must have jQuery library to make this work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!