How to do something if the user presses two keys in javascript

和自甴很熟 提交于 2019-12-11 01:36:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!