简体   繁体   English

检测JavaScript中的多个按键

[英]Detecting multiple key press in javascript

I'm attempting to detect a number of key combinations in javascript. 我正在尝试检测javascript中的许多按键组合。 I need to detect Ctrl + Left , Ctrl + Right , Right , and Left . 我需要检测Ctrl + LeftCtrl + RightRightLeft

So far I'm just trying to detect when Ctrl is pressed. 到目前为止,我只是试图检测何时按下Ctrl Here's what I have ( JSFiddle link ): 这是我所拥有的( JSFiddle链接 ):

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. 我想我不太了解JQuery的inArray应该如何工作,因为当我按任意键时,它只会返回-1。 The if statement also evaluates to true while I only want it to do that when Ctrl is pressed. 如果我只希望在按下Ctrl键时执行if语句,则if语句的计算结果也为true。 How can I fix this so that my if statement properly detects Ctrl being pressed? 如何解决此问题,以便我的if语句正确检测到按下了Ctrl I'll be able to figure the rest out once I get that working properly. 一旦我能够正常工作,我就能弄清楚其余的一切。

EDIT: Changed if-statement to evaluate inArray returning > -1 编辑:更改if语句以评估inArray返回> -1

In javascript you would need to capture the value of the window.event.ctrlKey to detect if the control key is being pressed. 在javascript中,您需要捕获window.event.ctrlKey的值以检测是否按下了控制键。 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: 这是一个函数示例,该函数可使用ctrl+v键盘快捷键阻止从剪贴板粘贴到字段中:

    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: 找出是否按下ctrl的最简单方法是测试ctrlKey属性的event对象:

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

JS Fiddle demo . JS小提琴演示

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: 因此,您可以简单地编写以下代码,而不是在函数中使用2个单独的if块:

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

Secondly, jQuery appends a very convenient property to event objects: ctrlKey . 其次,jQuery向事件对象添加了一个非常方便的属性: ctrlKey

In your keydown event handler, wrap the call to printKeys in an if statement: 在您的keydown事件处理程序中, printKeys的调用printKeys在if语句中:

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 最后,要检测ctrl +(其他任何键),只需检查事件的which属性是否与您要查找的keyCode之一相对应

Firstly, You're missing braces {} for the else case. 首先,在其他情况下,您缺少大括号{}

js Fiddle DEMO js小提琴演示

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

Run the Demo & watch the text "ctrl" show up while you click Ctrl key. 运行演示并观看文本“ ctrl”,同时单击Ctrl键。

e.ctrlKey is the easiest way to detect the Ctrl key click. e.ctrlKey是检测Ctrl键单击的最简单方法。

To detect Ctrl + left Demo here 在此处检测Ctrl +左演示

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

You can detect it easily using the returned event object. 您可以使用返回的event对象轻松检测到它。 This object also contains information about all control keys : 该对象还包含有关所有control keys

  • ctrlKey - does the Control key was pressed? ctrlKey是否按下了Control键?
  • shiftKey - does the Shift key was pressed? shiftKey是否按下Shift键?
  • altKey - does the if Alt key was pressed? altKey是否Alt键?

All of these properties are boolean values ( true , if button was pressed, otherwise` false ). 所有这些属性都是boolean值(如果按下按钮,则为true ,否则为false )。

Here is the demosntration of aforementioned properties in JSFiddle . 这是JSFiddle中上述属性的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM