简体   繁体   English

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

[英]How can I check that a key has been pressed?

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.但是函数getKey不能返回值。

So how can I check if the user pressed a key?那么如何检查用户是否按下了某个键?

EDIT : I need pure Javascript for this thing..编辑:我需要纯 Javascript 来做这件事..

You can do this in pure Javascript using the event object, without the need of external libraries such as jQuery.您可以使用事件对象在纯 Javascript 中执行此操作,而无需外部库,例如 jQuery。

To capture the keycode, just pass the event as parameter of getKey function:要捕获键码,只需将事件作为 getKey 函数的参数传递:

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

document.onkeyup = getKey;

Frequently used keyCode list:常用keyCode列表:

For a usefull list of keyCodes, you can check out this URL:有关有用的 keyCode 列表,您可以查看此 URL:

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

Setting the keyCode to a global variable:将 keyCode 设置为全局变量:

If you are interested in capturing the keyCode for later usage, you can do something like this:如果您有兴趣捕获 keyCode 以供以后使用,您可以执行以下操作:

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:将 keyCode 设置为事件源对象:

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

One way you could do it is using variables and then you could check that variable some were else...你可以做到的一种方法是使用变量,然后你可以检查变量是否还有其他......

for example例如

    var keypressed = "";
    document.onkeyup = function(e){

    if (typeof event !== 'undefined') {
        keypressed = event.keyCode;
      }
      else if (e) {
        keypressed = e.which;
      }  

  return false;   // Prevents the default action

}

You have to attach the event to the window global object and to set a function that listen to the event.您必须将事件附加到 window 全局对象并设置一个侦听事件的函数。 This sample show you how to track the keyup and keydown events.此示例向您展示如何跟踪keyupkeydown事件。

window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('keyup', onKeyUp, true);

function onKeyDown(evt) {
  // key up event as been fired
  console.log(evt.keyCode);
}

function onKeyUp(evt) {
  // key up event as been fired
  console.log(evt.keyCode);
}

See element.addEventListener on MDN for more details.有关更多详细信息,请参阅 MDN 上的element.addEventListener

You really should not be doing this but if you really must:你真的不应该这样做,但如果你真的必须:

var getKey = (function () {
  var currentKey = null;

  document.onkeyup = function (event) {
    // determine the pressed key (across browsers)
    // by inspecting appropriate properties of `event`
    // and update currentKey; E.g:
    currentkey = event.which ? event.which : window.event.keyCode;
  }

  return function () {
    return currentkey;
  }
})();

This will give you the last key user pressed.这将为您提供最后一次按下的关键用户。

If you need to get the currently pressed key (until released) then you need to attach keydown event to update currentKey variable and keyup event to set it to null .如果您需要获取当前按下的键(直到释放),那么您需要附加keydown事件以更新currentKey变量和keyup事件以将其设置为null

I would use jquery and do something like this:我会使用 jquery 并做这样的事情:

   // arrow keys click
$(document).keyup(function(e) {
    // left arrow
    if (e.keyCode == "37" ) {
        // left stuff
    // right arrow
    } else if (e.keyCode == "39") {
        // right stuff
    // up arrow
    } else if (e.keyCode == "38") {
        // up stuff
    // down arrow
    } else if (e.keyCode == "40") { 
        // down stuff
    }
});

etc, for the different key codes seen here http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes等等,对于这里看到的不同的关键代码http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

If you are attempting to run an event to test when a certain key is pressed, you can use this.如果您试图运行一个事件来测试某个键被按下时,您可以使用它。

document.addEventListener('keydown', function(event) {
    var key_code = event.keyCode;
    if (key_code === 38) {
        alert('test);
    } 
});

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

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