简体   繁体   English

按两个连续键以在JavaScript中触发事件

[英]press two continuous key to trigger an event in JavaScript

In Vim , you can press gg to go to the beginning of the document, Or press dd go delete the current line. Vim ,你可以按gg转到文档的开头,或者按dd去删除当前行。 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 //Do the action here ,只有在100毫秒内按g两次才会触发

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. 这很简单,干净(取决于你如何写它)和可扩展,添加更多命令非常简单,当然你改变它,以便你可以将参数传递给命令功能等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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