Get Correct keyCode for keypad(numpad) keys

前端 未结 6 1736
耶瑟儿~
耶瑟儿~ 2020-11-30 02:24

I\'m getting codes [96..105] by calling String.fromCharCode(event.keyCode) when pressing keys [0..9](digits) on the keypad. Th

6条回答
  •  眼角桃花
    2020-11-30 03:04

    There is a way to do this with keydown, if keypress is not workable due to event canceling needs, etc. Use an if() statement with this test:

    parseInt(event.keyIdentifier.substring(2),16) > 47 && parseInt(event.keyIdentifier.substring(2),16) < 58
    

    OR, with jQuery events:

    parseInt(event.originalEvent.keyIdentifier.substring(2),16) > 47 && parseInt(event.originalEvent.keyIdentifier.substring(2),16) < 58
    

    These examples assume "event" is the keydown event. keyIdentifier is a hexidecimal number that represents the unicode value for the related char. Using keyIdentifier, numbers from the numberpad / keypad AND the numbers above your QWERTY keyboard will all have the same values, 48 - 57 (U+0030 - U+0039), even with the keyDown event.

    Unicode values in the browsers will look like U+0030 or U+002F. Parse this string to only get the hexidecimal value, then use parseInt() with a radix of 16 to convert it to base-10.

提交回复
热议问题