且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查键是否被按下?

更新时间:2023-12-02 23:36:10

您可以使用事件对象在纯JavaScript中执行此操作,而不需要像jQuery这样的外部库。



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

  function getKey(e)
{
window.alert(键代码是:+ e.keyCode);
}

document.onkeyup = getKey;



常用的keyCode列表:



对于一个有用的keyCodes列表,你可以查看这个URL:



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



将keyCode设置为全局变量:



如果您有兴趣捕获keyCode为了以后使用,您可以这样做:

  var keycode =; 

(...)

函数getKey(e)
{
keycode = e.keyCode;
}

document.onkeyup = getKey;


window.alert(关键代码是:+ keycode);



将keyCode设置为事件源对象:



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

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

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

objectFromEvent.customProperty = keycode;
}


document.customProperty =;
document.onkeyup = getKey;

//现在的值在你的对象的customProperty中=)

window.alert(关键代码是:+ document.customProperty);


Well I searched on google but still didn't found the answer I was looking for.

I want to check if the user pressed a key, something like this -

if(document.onkeyup) {
   // Some Stuff here
}


I know I can do this, this way -

document.onkeyup = getKey;

But the function getKey cannot return values.

So how can I check if the user pressed a key?

EDIT : I need pure javascript for this thing..

You can do this in pure Javascript using the event object, without the need of external libraries such as jQuery.

To capture the keycode, just pass the event as parameter of getKey function:

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

document.onkeyup = getKey;

Frequently used keyCode list:

For a usefull list of keyCodes, you can check out this URL:

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

Setting the keyCode to a global variable:

If you are interested in capturing the keyCode for later usage, you can do something like this:

var keycode = "";

(...)

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

document.onkeyup = getKey;


window.alert("The key code is: " + keycode);

Setting the keyCode to the event source object:

If you don't like global variables, like me, you could also do something like this:

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);