ok, i need my code to check if minus/subtract/- was pressed, if it was pressed i want an alert box to pop. i tried with both 109
and 189
key codes but i still don't get the desired result. although i press "-"
i don't get that alert box
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Post some code. This works for me:
Full list of key codes here: http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
Don't do this in a
keydown
event handler - you put yourself at the mercy of different browsers' ideas about key codes and potential variation between key codes for different keyboard types. Do it in akeypress
event and then you can get the character code instead, which is what you actually want.All the information you could ever need about JavaScript key events: http://unixpapa.com/js/key.html
People are moving away from
event.keyCode
andevent.charCode
due to inconsistent implementations across browsers. Instead, useevent.code
. This is astring
field.Most browsers support
Array.includes
, so I tend to do the following:You can discover keyCodes this way:
The JavaScript charCodes, which you test for during a keypress event, are ASCII. 109 is the correct keyCode, if used in a keydown or keyup event.
"-" has a charCode of 45.
I hope this works for you, It detects users pressed keys and if it's the one your looking for it displays the alert, you may change the actual key to be any other key.