如何检查键是否被按下? [英] How can I check that a key has been pressed?

查看:148
本文介绍了如何检查键是否被按下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

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



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

  document.onkeyup = getKey; 

但是函数 getKey 不能返回值。



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



编辑:我需要纯JavaScript

解决方案

您可以使用事件对象在纯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);

这篇关于如何检查键是否被按下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆