最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Detecting multiple key press in javascript - Stack Overflow

programmeradmin8浏览0评论

I'm attempting to detect a number of key binations in javascript. I need to detect Ctrl + Left, Ctrl + Right, Right, and Left.

So far I'm just trying to detect when Ctrl is pressed. Here's what I have (JSFiddle link):

var keys = {};

$(document).keydown(function (e) {
    keys[e.which] = true;

    printKeys();
});

$(document).keyup(function (e) {
    delete keys[e.which];

    printKeys();
});

function printKeys() {
    var html = '';
    for (var i in keys) {
        html += '<p>i: ' + i + '</p>'
        if (!keys.hasOwnProperty(i)) continue;
        if ($.inArray(17, keys) > -1) 
            html += '<p>ctrl was pressed, return val: ' + $.inArray(17, keys) + '</p>'
    }
    $('#out').html(html);
}

I guess I don't really understand how JQuery's inArray is supposed to work because when I press any key, it just returns -1. The if statement also evaluates to true while I only want it to do that when Ctrl is pressed. How can I fix this so that my if statement properly detects Ctrl being pressed? I'll be able to figure the rest out once I get that working properly.

EDIT: Changed if-statement to evaluate inArray returning > -1

I'm attempting to detect a number of key binations in javascript. I need to detect Ctrl + Left, Ctrl + Right, Right, and Left.

So far I'm just trying to detect when Ctrl is pressed. Here's what I have (JSFiddle link):

var keys = {};

$(document).keydown(function (e) {
    keys[e.which] = true;

    printKeys();
});

$(document).keyup(function (e) {
    delete keys[e.which];

    printKeys();
});

function printKeys() {
    var html = '';
    for (var i in keys) {
        html += '<p>i: ' + i + '</p>'
        if (!keys.hasOwnProperty(i)) continue;
        if ($.inArray(17, keys) > -1) 
            html += '<p>ctrl was pressed, return val: ' + $.inArray(17, keys) + '</p>'
    }
    $('#out').html(html);
}

I guess I don't really understand how JQuery's inArray is supposed to work because when I press any key, it just returns -1. The if statement also evaluates to true while I only want it to do that when Ctrl is pressed. How can I fix this so that my if statement properly detects Ctrl being pressed? I'll be able to figure the rest out once I get that working properly.

EDIT: Changed if-statement to evaluate inArray returning > -1

Share Improve this question asked Oct 21, 2013 at 18:36 tnwtnw 13.9k15 gold badges71 silver badges114 bronze badges 2
  • 2 $.inArray <-- probably a good place to start if you don't understand how it works :) – Andrew Whitaker Commented Oct 21, 2013 at 18:39
  • @AndrewWhitaker Thanks Andrew, if statement now reads if ($.inArray(17, keys) > -1) Still doesn't pick up 17 being in the array despite html += '<p>i: ' + i + '</p>' popping out 17. – tnw Commented Oct 21, 2013 at 18:41
Add a ment  | 

5 Answers 5

Reset to default 3

In javascript you would need to capture the value of the window.event.ctrlKey to detect if the control key is being pressed. Here is an example of a function that would use to block pasting from the clipboard into a field using the ctrl+v keyboard shortcut:

    function BlockControlV() {
        var keyPressed = window.event.keyCode;
        var ctrlPressed = window.event.ctrlKey;
        if (ctrlPressed && keyPressed == 86) {

            var ClipBoardData = window.clipboardData.getData('Text')
            ClipBoardData = trim(ClipBoardData)

            if (ClipBoardData != '') {
                if (isNaN(ClipBoardData) == true) {
                    window.event.keyCode = 0;
                }
            }
            else {
                window.event.keyCode = 0;
            }
        }
    } 

Though not exactly relevant to what you're trying to do, you should be able to figure out what direction you should be heading.

The simplest way to find out whether the ctrl is pressed, is to test the event object for the ctrlKey property:

$(document).keypress(function(e){
    console.log(e.which, e.ctrlKey);
});

JS Fiddle demo.

I would have provided a more relevant demo, but I have no idea what that demo's meant to achieve.

First, keys is not an array- it is an object. So instead of the 2 separate if blocks in your function, you can write simply:

if (keys.hasOwnProperty(i)) {
  ...
}

Secondly, jQuery appends a very convenient property to event objects: ctrlKey.

In your keydown event handler, wrap the call to printKeys in an if statement:

if (e.ctrlKey) {
  printKeys();
}

Finally, to detect whether ctrl + (any other key), simply check whether the which property on the event corresponds to one of the keyCodes you are looking for

Firstly, You're missing braces {} for the else case.

js Fiddle DEMO

if (i == 17) {
    html += '<p>ctrl</p>';
} else {}

Run the Demo & watch the text "ctrl" show up while you click Ctrl key.

e.ctrlKey is the easiest way to detect the Ctrl key click.

To detect Ctrl + left Demo here

$(document).keydown(function(e){
    if(e.keyCode == 37 && e.ctrlKey)
        alert("Control + Left Clicked"); 
});

You can detect it easily using the returned event object. This object also contains information about all control keys:

  • ctrlKey - does the Control key was pressed?
  • shiftKey - does the Shift key was pressed?
  • altKey - does the if Alt key was pressed?

All of these properties are boolean values (true, if button was pressed, otherwise` false).

Here is the demosntration of aforementioned properties in JSFiddle.

发布评论

评论列表(0)

  1. 暂无评论