特定键的keydown + keyup事件 [英] keydown + keyup events for specific keys

查看:117
本文介绍了特定键的keydown + keyup事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我按住某些键时,我正在尝试更改背景颜色。例如,当按住r键时,背景应为红色。当'r'键不再被按下时,背景应该默认为白色。

I'm trying to make the background color change when certain keys are held down. For example, when the 'r' key is being held down, the background should be red. When the 'r' key is not being pressed anymore, the background should default to white.

$(document).ready(function () {
    $('body').keydown(function(e){
        if(e.keyCode == 114){
            $(this).css({'background':'red'});  
        }
        if(e.keyCode == 121){
            $(this).css({'background':'yellow'});
        }
    });
    $('body').keypress(function(e){
        if(e.keyCode == 114){
            $(this).css({'background':'red'});  
        }
        if(e.keyCode == 121){
            $(this).css({'background':'yellow'});
        }
    });
    $('body').keyup(function(e){
        if(e.keyCode == 114){
            $(this).css({'background':'white'});
        }
        if(e.keyCode == 121){
            $(this).css({'background':'white'});
        }
    });

});

我遇到的问题是密钥不能专门用于每个密钥。

The problem I'm having is that keyup is not working specifically for each individual key.

    $('body').keyup(function(e){
        $(this).css({'background':'white'});
    });

我知道如果我从keyup完全删除if条件那么它会表现我说我想要它to - 但我希望以后能够使用特定键的keyup做不同的事情。例如,当只释放'b'键时,它可能会在屏幕上显示你刚刚发布了b键!。如何跟踪特定键的keydown和keyup事件,并为每个键发生不同的事情?我知道这也不是很有组织(我对这个东西很新)所以如果有一个完全不同的更好的方法来做这个......

I know if I remove the if conditionals from keyup altogether then it will behave how I said I wanted it to — but I want to be able to do different things later on using keyup with specific keys. For example, when just the 'b' key is released, maybe it will say something on the screen like "You just released the b key!" How can I keep track of keydown and keyup events for specific keys and make different things happen for each? I know this isn't very organized either (I'm pretty new to this stuff) so if there's a completely different and better way of doing this...

推荐答案

现场演示

FYI R = 82

FYI R = 82

$(document).ready(function () {

    $('body').on('keydown keyup',function(e){
      var color = e.type=="keydown" ? 'red' : 'white' ;
      if(e.which==82){
          $(this).css({background: color});  
      }
    });

});

一个面向对象的示例是为a创建一个动作列表所需的KEY:
现场演示

An object oriented example would be to create a list of actions for a desired KEY:
LIVE DEMO

$(document).ready(function () {

    $('body').on('keydown keyup', function( e ) {

      var key = e.which;
      var io  = e.type=="keydown" ? 0 : 1; // "0"if keydown; "1" if keyup
      var keyAction = {                    // Object to store our stuff
//  keyCode : [(0)KEYDOWN, (1)KEYUP]
        82  : ['red' ,'white'],            // R key
        66  : ['blue','white']             // B key  (last one without comma!)
      };
      var propObj = {};                    // Object to store property + value for jQuery methods
      var keyArr = keyAction[key];

      if(typeof keyArr != 'undefined') {   // Test keyArr (82, 66) is returned/populated to prevent errors
         propObj.background = keyAction[key][io];   // Created the jQ Method's object e.g: {background:"red"}
         $(this).css(propObj);             // Finally create / use 
      }

    });

});

我使用的是三元运算符(?:)

var io = e.type=="keydown" ? 0 : 1;

你也可以使用NOT按位运算符,如:

you can also use the NOT bitwise operator like:

var io = ~~(e.type=="keyup"); // evaluating false|true == 0|1

您只需要知道哪个事件是发生(从指定的keydown/keyup)并获得所需的数组位置 [0] [1] 您需要的属性值,例如: [red] [white] (其中red== 0和white== 1)

any way you just need to know which event is occurring (from the designated "keydown" / "keyup") and get the desired array position [0],[1] of the property value you need, e.g: ["red"],["white"] (where "red" == 0 and "white" == 1)

非按位运算符的演示

更多 <上面的href =http://jsbin.com/awolab/13/edit>高级方式DEMO 也会添加到你的列表中

An more advanced way DEMO of the above would be to add to your list also


  • 要定位的元素,

  • 要使用的jQuery方法,

  • 要应用该方法的属性

这将导致:

$(document).ready(function () {

    $('body').on('keydown keyup', function(e) {

      var keyAction = {

        82  : ['body', 'css', "background", ['red','white'] ],  // R key
        66  : ['body', 'css', "background", ['blue','white'] ], // B key
        72  : ['h1', 'animate', "top", [100,30] ]       // H key

      },
          key = e.which,              // Get the keyCode
          keyArr = keyAction[key],    // get our array from our list
          io  = e.type=="keydown" ? 0 : 1, // io will be 0 || 1 depending if key is down or up
          element,
          method,
          property={}; // the Method Properties Object will look like e.g: {"background":"red"}

      if(typeof keyArr != "undefined"){
         element = keyArr[0], 
         method = keyArr[1],
         property[keyArr[2]] = keyArr[3][io];       
         $(element)[method](property);  // do stuff
      }

      console.log( key, io, element, method, property);

    });

});

您甚至可以按住 B 键并按 H 执行同步操作的关键。

You can even hold down your B key and press the H key to do simultaneous actions.

如果您有任何疑问(我认为您可以),请随时提出。

If you have questions (I think you would) feel free to ask.

编辑

如果你想控制CSS类而不是:

If you want to control CSS classes than do like:

http://jsbin.com/awolab/22/edit

这篇关于特定键的keydown + keyup事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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