handle long key presses in javascript

后端 未结 3 963
悲哀的现实
悲哀的现实 2021-01-03 15:25

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 cod

相关标签:
3条回答
  • 2021-01-03 15:40

    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;
    }
    
    0 讨论(0)
  • 2021-01-03 15:46

    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.

    0 讨论(0)
  • 2021-01-03 16:04

    Try keyup:

    var myJSON={65:[],83:[],68:[],70:[],71:[]};
    window.onkeyup=function(e){
        console.log(myJSON);
        myJSON[parseInt(e.keyCode)].push(1);
    }
    
    0 讨论(0)
提交回复
热议问题