最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - event.key is undefined in mobile browsers for keyup, keydown and keypress - Stack Overflow

programmeradmin4浏览0评论

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:

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

Share Improve this question edited Aug 1, 2017 at 10:55 Philip Feldmann asked Aug 1, 2017 at 9:19 Philip FeldmannPhilip Feldmann 8,3757 gold badges44 silver badges66 bronze badges 5
  • What kind of device and keyboard are you using? – Aron Commented Aug 1, 2017 at 9:20
  • Tested on iPhone 6 Safari and Chrome, Nexus 6 Chrome, One Plus 3 and 3T Chrome and a Honeywell Android Scanner also Chrome using both the integrated scanner as input and the native digital keyboard of each OS. Didn't work on any device. – Philip Feldmann Commented Aug 1, 2017 at 9:22
  • You might start with valid html. What do parsers make of <div id="#test" />? Safari at least sees it as a DIV open tag with no closing tag, so error corrects to place everything after it into the div. – RobG Commented Aug 1, 2017 at 9:26
  • It's just a demo to test the error for a bigger application. I've already changed the markup to be valid, but like I said, the error is not that the selector is undefined but the key-attribute of the event, which is bound to document. – Philip Feldmann Commented Aug 1, 2017 at 10:45
  • 2 How is this still an issue in Chrome five years later?? – knarf Commented Oct 4, 2022 at 20:10
Add a comment  | 

2 Answers 2

Reset to default 11

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

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)

  1. 暂无评论