问题
Below code accepts a character and prints character using keycode(String.fromCharCode). Issue arises when you enter special character like .
or ?
.
function logChar(e){
var keyCode = e.which || e.keyCode;
var char = String.fromCharCode(keyCode);
console.log(char)
}
<input type="text" onkeydown="logChar(event)" />
Can someone explain why is it returning different value and how to get same value?
Thanks in advance!
回答1:
That's because keyCode
and charCode
are different. String.fromCharCode
assumes that the input is unicode (so A is 65), and for the letter and number keys, they will match... sort of. You will notice that 'a' and 'A' as a keyCode both come out as 65, but 'a' is 97! So keyCode is just an identifier for the actual key on the keyboard that you press and is not unicode.
That's why the numpad 0-9 gives different codes too. If you want to map the key presses, use a site like this. But note you will never get the exact character out again.
来源:https://stackoverflow.com/questions/34768354/string-fromcharcode-issue-for-special-characters-in-javascript