2015-03-31 141 views
1

我试图在多次按下某个按键时运行一个功能。我怎样才能在JavaScript中做到这一点?检查一个按键是否被按下两次

我想这样

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

你不能做同步那样。由于没有doublekeypress事件,所以您必须通过记住最后一次按键和按下它的时间来检测它。 – Touffy 2015-03-31 08:02:50

+1

可能重复[Javascript - 检查键是否在5秒内按两次](http://stackoverflow.com/questions/23820862/javascript-check-if-key-was-pressed-twice-within-5-secs) – D4V1D 2015-03-31 08:02:52

回答

1

如果你不介意者均基于时间的关键压制,存储上次记者在一个变量和比较:

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

如果你想检查键将整个单词或句子按下两次,然后将每个关键代码放入数组中,并且每次都与数组元素进行匹配,如果存在则表示按下了两次。

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

你可以定义一个全局变量,做这样的

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

+0

如果(pressCount == 2)将'pressCount'重置为'0'' – halex 2015-03-31 08:10:45

相关问题