如何在javascript中捕获双键按? [英] How to trap double key press in javascript?

查看:98
本文介绍了如何在javascript中捕获双键按?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够捕获双键按下(例如Char T)以进行一些特殊处理。我希望按键发生得足够快,不能被解释为两次单独的按下,就像双击一样。
我有什么想法可以实现这个目标吗?

I would like to be able to trap the double key press (for the Char T for example) in order to do some special processing.I would like the key presses to happen fast enough to not be interpreted as two separate presses, just like the double click. Any ideas how i can achieve this?

推荐答案

当按键被击中时,请记下时间。然后将它与您记下最后时间点击的时间进行比较。

When the key(s) are hit, make a note of the time. Then compare it with the time you noted the last time they key(s) were hit.

如果差异在您的阈值范围内,请考虑它是双倍的。否则,不要。粗略的例子:

If the difference is within your threshold, consider it a double. Otherwise, don't. Rough example:

var delta = 500;
var lastKeypressTime = 0;
function KeyHandler(event)
{
   if ( String.fromCharCode(event.charCode).toUpperCase()) == 'T' )
   {
      var thisKeypressTime = new Date();
      if ( thisKeypressTime - lastKeypressTime <= delta )
      {
        doDoubleKeypress();
        // optional - if we'd rather not detect a triple-press
        // as a second double-press, reset the timestamp
        thisKeypressTime = 0;
      }
      lastKeypressTime = thisKeypressTime;
   }
}

这篇关于如何在javascript中捕获双键按?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆