如何检查是否按下了某个键?

jul*_*ian 6 javascript events dom-events

好吧,我在谷歌上搜索,但仍然没有找到我想要的答案。

我想检查用户是否按下了一个键,就像这样 -

if(document.onkeyup) {
   // Some Stuff here
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做,这样 -

document.onkeyup = getKey;
Run Code Online (Sandbox Code Playgroud)

但是该函数getKey不能返回值。

那么如何检查用户是否按下了某个键?

编辑:我需要纯 Javascript 来做这件事..

can*_*cas 5

您可以使用事件对象在纯 Javascript 中完成此操作,而不需要 jQuery 等外部库。

要捕获键码,只需将事件作为 getKey 函数的参数传递即可:

function getKey(e)
{
    window.alert("The key code is: " + e.keyCode);
}

document.onkeyup = getKey;
Run Code Online (Sandbox Code Playgroud)

常用键码列表:

有关有用的密钥代码列表,您可以查看以下 URL:

http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

将 keyCode 设置为全局变量:

如果您有兴趣捕获 keyCode 以供以后使用,您可以执行以下操作:

var keycode = "";

(...)

function getKey(e)
{
    keycode = e.keyCode;
}

document.onkeyup = getKey;


window.alert("The key code is: " + keycode);
Run Code Online (Sandbox Code Playgroud)

将 keyCode 设置为事件源对象:

如果你像我一样不喜欢全局变量,你也可以这样做:

function getKey(e)
{
    keycode = e.keyCode;

    var objectFromEvent = e.currentTarget ? e.currentTarget : event.srcElement;

    objectFromEvent.customProperty = keycode;
}


document.customProperty = "";
document.onkeyup = getKey;

// now the value is in the "customProperty" of your object =)

window.alert("The key code is: " + document.customProperty);
Run Code Online (Sandbox Code Playgroud)