简体   繁体   English

来自箭头键的键盘键码

[英]Keyboard keycode from arrow keys

I'm trying to get a response for when visitor uses the keys right and left我试图获得访问者何时使用左右键的响应

<script>
  $(document).keypress(function(event) {
    key = String.fromCharCode(event.which)
    if(key == '37' || key == '39') {
      $('main').html('You pressed : ' + key)
      event.preventDefault()
    }
  });
</script>

It's not working.它不起作用。 what did work was the line什么工作是线

if(key == 'a')

I used this table to find the code https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes我用这张表找到了代码https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Is it because jQuery has different table?是因为 jQuery 有不同的表吗? or maybe I should load JavaScript as well?或者我也应该加载 JavaScript? then how do I do use the two of them?那么我该如何使用它们两个呢? (jQuery and JavaScript?)? (jQuery 和 JavaScript?)?

EDIT:编辑:

I think I got it我想我明白了

String.fromCharCode(event.which)

JavaScript can't read strings as numbers? JavaScript 无法将字符串读取为数字? do I need to use different function?我需要使用不同的功能吗? I'm new to this can you tell me what to do?我是新手,你能告诉我该怎么做吗?

I find for myself that when I go to implement these sorts of "get item from event", that a simple console.log(event) does wonders.我发现当我去实现这些类型的“从事件中获取项目”时,一个简单的console.log(event)会产生奇迹。 I'd start with:我会从:

$('body').on('keypress', function(evt){
    console.log('Event: ', evt);
});

Then, press the right and left arrow keys and see what happens.然后,按左右箭头键,看看会发生什么。

First, an observation: I note that you're comparing the string '37' , which is distinct from the integer value 37 .首先,观察:我注意到您正在比较字符串'37' ,它与整数值37 The former is two or four bytes (depending on how the JS implementation stores characters), while the latter is one byte.前者是两个或四个字节(取决于 JS 实现如何存储字符),而后者是一个字节。 Is that your intention after reading the appropriate APIs?这是您在阅读适当的 API 后的意图吗?

Second, as a specific suggestion, if you're using jQuery, take advantage of it's normalization routines.其次,作为一个具体的建议,如果您使用 jQuery,请利用它的规范化例程。 In this case, event.which is returning 0, but you can use event.keyCode which is probably what you want to compare:在这种情况下, event.which返回 0,但您可以使用event.keyCode这可能是您想要比较的内容:

if ( 37 === event.keyCode ) {
  // ...
}
else if ( 39 === event.keyCode ) {
  // ....
}

What you want to use is the keydown event.您要使用的是keydown事件。 Also, no reason to use the String.fromCharCode , you can just compare the integers.此外,没有理由使用String.fromCharCode ,您可以只比较整数。 Something like this would work像这样的东西会起作用

$(document).keydown(function(event) {
  if (event.which == 37 || event.which == 39) {
    var key = event.which == 37 ? 'left' : 'right';
    $('main').html('You pressed : ' + key)
    event.preventDefault()
  }
})

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

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