keydown + keyup events for specific keys

老子叫甜甜 提交于 2019-11-30 03:54:03

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



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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!