简体   繁体   中英

Check if a key is pressed two times

I am trying to run a function once a key is pressed more than one time. How can I do that in JavaScript?

I was thinking something like

if (e.keyCode == 27) {
      if (e.keyCode == 27) {
           alert("pressed two times");
      }
}

If you don't mind the time btw the key pressings, store last press in a variable and compare:

var lastKeyCode;
if (e.keyCode == 27) {
      if (e.keyCode == lastKeyCode;) {
           alert("pressed two times");
      } else {
           lastKeyCode = e.keyCode;
      }
}

you can define a global var and do like this

 var pressCount = 0; // global if (e.keyCode == 27) { pressCount++; if (pressCount == 2) { alert("pressed two times"); } } 

If you want to check key pressed two times in a whole word or sentence then put each key code into array and match at every time with array elements if exist mean it pressed two times.

var KeyCodes;
if (e.keyCode == 27) {
      if (jQuery.inArray( e.keyCode, KeyCodes)) {
           //mean two time exist
      } else {
           KeyCodes.push(e.keyCode);
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM