问题
I have using iframe
in my application. I have return string value when i press any key from keyboard.
All other keys are returned expected string value except key 219 ,220, 221
.
These keys are returned "Û", "Û", "Ý"
these values.
But i'm expected "[", "]", "\"
these string values.
How can I get the correct character from those keys?
回答1:
keydown
and keyup
use keycodes that can vary from keyboard to keyboard depending on your input keyboard type (different keyboards for different regions, etc.).
For printable characters, you need to wait for the browser to issue keypress
, which gives you the translated value of the key to character (if there is one), which it gives you in charCode
(although paranoically I tend to do e.charCode || e.which
; maybe that's silly). For instance, there's a key on my keyboard that, under *nix the way I have it configured, is keycode 220 for keydown
/keyup
and generates the character £
. But in a virtual machine running Windows with a different keyboard layout, that same key is keycode 220 for keydown
/keyup
but generates the character #
.
Example:
function handler(e) {
var msg = "Received " + e.type;
if (e.type === "keypress") {
// keypress
msg += " '" + String.fromCharCode(e.charCode || e.which) + "'";
} else {
// keydown/keyup
msg += " " + (e.which || e.keyCode);
}
console.log(msg);
}
document.addEventListener("keydown", handler, false);
document.addEventListener("keyup", handler, false);
document.addEventListener("keypress", handler, false);
Click here to focus the document, then press keys.
来源:https://stackoverflow.com/questions/38846692/key-down-keycode-not-return-expected-string-value