Key down keycode not return expected string value

好久不见. 提交于 2019-12-23 02:19:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!