keydown combination
how do i check if a combination of keys are pressed with jquery?
lets say i want to fire up an alert only when the up and down arrow keys are pressed at the sam开发者_如何学Goe time.
right now im just using:
switch (event.which) {
case 40:
alert('down');
break;
case 38:
alert('up');
break;
case 37:
alert('left');
break;
case 39:
alert('right');
break;
}
Set flags. When one key goes down, if it's a certain keyCode, set your flag myKeyIsDown = true
. When it comes up, set the flag back to false. When your second key goes down, if it is of a certain keyCode and your myKeyIsDown
flag is true, you've got two keys down.
I found this useful: How to detect simultanious two key press from the Javascript ?.
It's pure javascript though. You can also change first method to work with event.which
.
And no flags.
Fix: For first method to work with up + down + R, you should use this method:
function KeyPress(e) {
for (i = 0; i < KPAry.length; i++) {
if (e == KPAry[i]) {
return;
}
} // for (i=0;i<KPAry.length;i++)
if (e != 17 && e != 18 && e != 82 && e!=38 && e!=40) {
KPAry = new Array();
} else {
KPAry[KPAry.length] = e;
}
if (KPAry.length == 3) {
if (KPAry[0] == 17 && KPAry[1] == 18 && KPAry[2] == 82) {
alert('Keys Pressed\nctrl+alt+R ');
} else if (KPAry[0] == 38 && KPAry[1] == 40 && KPAry[2] == 82) {
alert('Keys Pressed\nup+down+R ');
}
KPAry = new Array();
} // if (KPAry.length==3)
} // function KeyPress(e)
You could try using a plugin like this (demo)
One suggestion in followup to another answer, you might want to stop the cascade of the event on the second key press, which could be done similar to this: (put your logic in of course)
/* handle special key press */
function checkCptKey(e)
{
var shouldBubble = true;
switch (e.keyCode)
{
// user pressed the Tab
case 9:
{
$(".someSelect").toggleClass("classSelectVisible");
shouldBubble = false;
break;
};
// user pressed the Enter
case 13:
{
$(".someSelect").toggleClass("classSelectVisible");
break;
};
// user pressed the ESC
case 27:
{
$(".someSelect").toggleClass("classSelectVisible");
break;
};
};
/* this propogates the jQuery event if true */
return shouldBubble;
};
/* user pressed special keys while in Selector */
$(".mySelect").keydown(function(e)
{
return checkCptKey(e);
});
精彩评论