Detect printable keys

前端 未结 2 1544
不知归路
不知归路 2020-12-09 09:33

I need to detect whether the key which has just been pressed is a printable key, like a character, possibly accented, a number, a space, a punctuation symbol and so on, or a

2条回答
  •  误落风尘
    2020-12-09 10:02

    Luckily, this task is much easier in modern browsers. You can now use KeyboardEvent.key to detect a printable key via its length.

    test.onkeydown = e => {
      let isPrintableKey = e.key.length === 1;
      alert(`Key '${e.key}' is printable: ${isPrintableKey}`);
    }

    Besides that, you can also detect any other keys from the list, like Enter, Delete, Backspace, Tab, etc.

    This method is much more reliable simply because unlike event.which, event.key is already standardized.

提交回复
热议问题