问题
So I wrote this script so that you can have keyboard shortcuts on your website, and I was wondering how to do multiple keys (ie instead of doing just the "left arrow" key, it would be the "ctrl + left arrow". Here's my current syntax:
var arrow = {
left: 37,
up: 38,
right: 39,
down: 40
};
function DoSomething() {}
$(document).ready(function() { // requires jQuery
$("body").keydown(function(event) {
if(event.keyCode == arrow.left) {
DoSomething();
}
}
}
But what I would like to do is something like this:
var arrow = {
left: 37,
up: 38,
right: 39,
down: 40
},
ctrl = 17;
function DoSomething() {}
$(document).ready(function() { // requires jQuery
$("body").keydown(function(event) {
if(event.keyCode == ctrl && arrow.left) {
DoSomething();
}
}
}
回答1:
The event object provided in jQuery tells you if the ctrl key is being pressed.
$(document).on("keydown", function (event) {
if (event.ctrlKey && event.which === arrow.left) {
console.log("You pressed left, and control.");
}
});
Demo: http://jsfiddle.net/zcMXR/
回答2:
jQuery already does that. Along with tracking which key was pressed, you can also get information on whether the key was pressed in combination with alt, ctrl or shift with the properties shown below:
$(document).keydown(function(e) {
console.log('key code is: ' + e.which + ' ' + (e.ctrlKey ? 'Ctrl' : '') + ' ' +
(e.shiftKey ? 'Shift' : '') + ' ' + (e.altKey ? 'Alt' : ''));
});
So, to check if the key combo is Ctrl + Up, your condition is going to look like:
if( e.which == 38 && e.ctrlKey ){
console.log('You pressed Ctrl+Up');
...
}
来源:https://stackoverflow.com/questions/13477304/how-to-do-something-if-the-user-presses-two-keys-in-javascript