开发者

press two continuous key to trigger an event in JavaScript

开发者 https://www.devze.com 2023-01-31 01:17 出处:网络
In Vim, you can press gg to go to the beginning of the document, Or press dd go delete the current line. How to implement similar behavior in a web page? I mean, in a web page environment, how can I c

In Vim, you can press gg to go to the beginning of the document, Or press dd go delete the current line. How to implement similar behavior in a web page? I mean, in a web page environment, how can I capture开发者_开发技巧 two continuous key press event to trigger an event?

Thanks.


You would need to monitor all key press events and when you find a key that is possibly the first in a multi-press combo, start a timer. If the second key in the combo is pressed while the timer is active, do something.

eg (pseudocode)

//for gg
var inCombo = false;
function KeyPress(Key) {
   if(Key=='g') {
      if(!inCombo) {
          inCombo = true;
          setTimeout('inCombo=false;', 100);
      } else {
          //Do the action here
      }
   }
}

The //Do the action here, will only fire if g is pressed twice within 100ms


You can't. Simply register the normal key event and push the keys to an array.

Now you can call a function which checks for the commands:

 // More or less pseudo code
 function deleteLine(){};
 function copyLine(){};      

 var commands = {'dd': deleteLine, 'yy': copyLine};    

 function onKeyPress(e) {
     keyList.push(e.key);

     // in this example keyList = ['d', 'y', 'i', 'd', 'd']
     var result = handleEvent();
 }

 function handleEvent(keyList) {
      // more pseudo code follows

      var cmds = commands.keyValue.sortByLengthDescending();
      for(var c in cmds) {

          // match the keys
          var ckey = c.split('');
          for(var i = keyList.length; i >= 0; i--) {
              if (keyList[i] !== ckey.shift()) {
                  break;
              }
              if (ckey.length === 0) {
                  return commands[c]();
              }
          }
      }
 }

This is simple, clean (depends on how exactly you write it) and scalable, adding more commands is pretty easy, of course you change it so that you can pass parameters to the command function etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消