使用JavaScript KeyCode - 一次按下多个键

时间:2013-02-04 08:12:11

标签: javascript javascript-events key keypress

我从用户B1KMusic找到了这个解决方案:JavaScript multiple keys pressed at once

代码:

map={}//I know most use an array, but the use of string indexes in arrays is questionable
onkeydown=onkeyup=function(e){
    e=e||event//to deal with IE
    map[e.keyCode]=e.type=='keydown'?true:false
    /*insert conditional here*/
}

if(map[17]&&map[16]&&map[65]){//CTRL+SHIFT+A
    alert('Control Shift A')
}else if(map[17]&&map[16]&&map[66]){//CTRL+SHIFT+B
    alert('Control Shift B')
}else if(map[17]&&map[16]&&map[67]){//CTRL+SHIFT+C
    alert('Control Shift C')
}

这有效,但我遇到了问题:按下CTRL + SHIFT + B后收到警报后,按任意键,我再次收到警报。

B1KMusic发现了这个工作:

 if(map[17]&&map[16]&&map[65]){//CTRL+SHIFT+A
    alert('Oh noes, a bug!')
}
//When you Press any key after executing this, it will alert again, even though you 
//are clearly NOT pressing CTRL+SHIFT+A
//The fix would look like this:

 if(map[17]&&map[16]&&map[65]){//CTRL+SHIFT+A
    alert('Take that, bug!')
    map={}
}
//The bug no longer happens since the map object is cleared

我试过了,问题仍然存在。

0 个答案:

没有答案