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

后端 未结 2 1012
醉梦人生
醉梦人生 2021-01-17 11:28

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) <

相关标签:
2条回答
  • 2021-01-17 11:41

    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);
      }
    }
    
    0 讨论(0)
  • 2021-01-17 11:52

    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;
    })
    
    0 讨论(0)
提交回复
热议问题