keydown + keyup events for specific keys

2019-02-03 17:45发布

问题:

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

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...

回答1:

LIVE DEMO

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

});

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 
      }

    });

});

where instead of the Ternary Operator (?:) I used:

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

you can also use the NOT bitwise operator like:

var io = ~~(e.type=="keyup"); // evaluating false|true == 0|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)

DEMO with NOT bitwise operator


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

  • elements to target,
  • a jQuery method to use,
  • the properties for that method to apply

which would result in:

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

    });

});

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.

EDIT

If you want to control CSS classes than do like:

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



回答2:



$().ready(function() {
  $('body').on("keyup keydown", function() {
    if(e.keyCode == 114 || e.keyCode = 121) {
      $(this).toggleClass("key" + e.keyCode)
    }
  })
})


Now just match the css rules with your css classes