event.key is undefined in mobile browsers for keyup, keydown and keypress

≯℡__Kan透↙ 提交于 2020-02-29 22:05:41

问题


The following code is supposed to simply suppress any key press and add the pressed key to a div instead. This works fine on desktop, however on mobile (safari and chrome) event.key is undefined.

<html>
    <head></head>
    <body>
        <input />
        <div id="#test"></div>
        <script>
            var str = '';
            var el = document.getElementById('#test');
            document.addEventListener('keypress', function(event) {
                str += event.key;
                event.preventDefault();
                el.innerHTML = str;
            })
        </script>
    </body>
</html>

event.keyCode and event.keyIdentifier are both available but casting those to a string will give me unwanted results on different keyboard layouts and languages, especially with special characters.

Is there anyway to get the value of the key directly?

Here's a codepen example just in case: https://codepen.io/anon/pen/pryYyQ


回答1:


The only workaround is to get the keycode and cast it to String:

var str = '';
var el = document.getElementById('#test');
document.addEventListener('keypress', function(event) {
  const currentCode = event.which || event.code;
  let currentKey = event.key;
  if (!currentKey) {
    currentKey = String.fromCharCode(currentCode);
  }
  str += currentKey;
  event.preventDefault();
  el.innerHTML = str;
})



回答2:


Since there is no character representation for control characters like up, down, left or right, you need to hardcode the character implementation in the code itself. I used Window.event.KeyCode event from document.onkeydown event listener and it works. Here is my solution:

window.onload = function() {
  try {
    var el = document.getElementById("#test");
    var str = '';
    document.onkeydown = function() {
      var currentKey = window.event.keyCode;
      switch (currentKey) {
        case 40:
          str = "down";
          break;
        case 37:
          str = "left";
          break;
        case 39:
          str = "right";
          break;
        case 38:
          str = "up";
          break;
      }
      event.preventDefault;
      e1.innerHTML = str;

    };

  } catch (e) {
    alert(e.message);
  }
}


来源:https://stackoverflow.com/questions/45433810/event-key-is-undefined-in-mobile-browsers-for-keyup-keydown-and-keypress

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