开发者

How to detect if shift has been released?

开发者 https://www.devze.com 2023-03-15 23:26 出处:网络
I want to be able to run a function when the shift key is released. I know the shift key can be detected with something like:

I want to be able to run a function when the shift key is released.

I know the shift key can be detected with something like:

$(window).bind("keydown keyup", function(ev) { ... });

It works very well for detecting key combinations (e.g. shift+a). Problem is, if you want to detect the shift key itself, this triggers a keydown with ev.shiftKey=false, ev.which=16 and a keyup with ev.shiftKey=开发者_如何转开发true, ev.which=16. I've tried to attach an event to this combination on keyup, but this fail in a very subtle way when both shift keys are pressed: for the second shift key you get both keyup/keydown with true,16 and then you get another keyup with true,16 when the first shift key is released.

Is there any clean way to do this? Or should I just ignore the two shift key case?


Someone pressing both SHIFT keys at the same time is improbable, unless they are intentionally trying to break your application. You can't design (read: waste time) coding edge cases, when 99% of your users in this case would never be pressing both keys.

Your logic for determining key presses is sound. Set a variable and increment/decrement it based on the presses, and if it equals 0, then they've got nothing pressed. Presto bammo.

EDIT: OR just do what Brian said in his comment! :)

0

精彩评论

暂无评论...
验证码 换一张
取 消