Combining keycode events in jQuery

2019-05-27 02:04发布

问题:

I'm building a virtual keyboard in jQuery, using keycode events to tigger an append, but keycode combinations are throwing me for a loop. Here's an example:

I want to append a questionmark only when both the SHIFT key (keycode 16) and slash key (keycode 191) are pressed together. I thought the && operator would help, but this only appends the slash:

$(document).keydown(function(e) { 

    if (e.keyCode == 16 && e.keyCode == 188  ) { 
         $('#mydiv').append('<span>?</span>');
     }

});

Any suggestions or idea why && isn't working, and what might work? Thanks!

回答1:

Checking e.keyCode == 16 && e.keyCode == 188 won't do anything useful because e.keyCode won't be both 16 and 188 at the same time. The && operator is a logical conjunction so it evaluates to true if the expressions on both sides of it are true.

I think you want to look at e.shiftKey; if that's true then the Shift key is down, if e.shiftKey is false then Shift is not down:

if(e.shiftKey && e.keyCode == 191) {
    // ?
}
else if(!e.shiftKey && e.keyCode == 191) {
    // /
}


回答2:

Because each key creates its own keydown event, it will never be possible for keyCode to equal both 16 and 188.

Luckily the SHIFT state is stored in event.shiftKey :)



回答3:

try this

$(document).keydown(function(e) {
  if (e.shiftKey){
     if (e.which == 188) { 
         alert('both');
     }

  }
});