Combining keycode events in jQuery

梦想的初衷 提交于 2019-12-22 17:54:11

问题


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

  }
});


来源:https://stackoverflow.com/questions/7962025/combining-keycode-events-in-jquery

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