handle long key presses in javascript

2020-02-29 18:37发布

I am trying to get keys from users using javascript and storing it in a javascript object.
i.e when i press 'A', 1 should be added to myJSON[65].
The following code works perfectly but if users press a key for a long time it will detect it as multiple key presses. I don't wan't that. is there a better way to do this????

var myJSON={65:[],83:[],68:[],70:[],71:[]};
window.onkeydown=function(e){
    console.log(myJSON);
    myJSON[parseInt(e.keyCode)].push(1);
}

http://jsfiddle.net/mp2v7/

Thanx in advance..

3条回答
对你真心纯属浪费
2楼-- · 2020-02-29 19:24

Try keyup:

var myJSON={65:[],83:[],68:[],70:[],71:[]};
window.onkeyup=function(e){
    console.log(myJSON);
    myJSON[parseInt(e.keyCode)].push(1);
}
查看更多
地球回转人心会变
3楼-- · 2020-02-29 19:32

Try this:

var keyStopper=false;
window.onkeydown=function(e){
 if(keyStopper)return e.keyCode;
 keyStopper=true;
console.log(myJSON);
myJSON[parseInt(e.keyCode)].push(1);
}
window.onkeyup = function(e){
keyStopper=false;
}
查看更多
▲ chillily
4楼-- · 2020-02-29 19:42

Use keydown and keyup events only. They work as their name implies, keydown : a single event when a key is pressed. keyup - a single event when the key is released.

查看更多
登录 后发表回答