Combining keycode events in jQuery

2019-05-27 02:05发布

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!

3条回答
贼婆χ
2楼-- · 2019-05-27 02:47

try this

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

  }
});
查看更多
狗以群分
3楼-- · 2019-05-27 03:03

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) {
    // /
}
查看更多
Bombasti
4楼-- · 2019-05-27 03:10

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 :)

查看更多
登录 后发表回答