How to find out event.key from event.code

人盡茶涼 提交于 2019-12-13 03:32:18

问题


Recently I heard about new ways of working with various keyboards, using KeyboardEvent.code and KeyboardEvent.key. It's a great feature but is there a way of getting event.key when you know event.code?

Let's say that the user printed 'w' letter and triggered an event with event.code = 'KeyW' that you saved somewhere. Then later you need to find out the event.key value that the user would print if he triggered that event again (with event.code = 'KeyW'). Maybe I should programatically trigger key pressing somehow?

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <p id="demo">asd</p>
  <script>

window.addEventListener('keydown', KeyDownHandler, false);

let key_code = undefined;    

function KeyDownHandler(event) {
  let key_code = event.code;
  console.log(key_code);
  document.getElementById("demo").innerHTML = key_code;
}
    
function CodeToKey(key_code)
{
  // I want this function to be able to translate 'KeyW' to 'w'
}

  </script>
  
</body>
</html>

来源:https://stackoverflow.com/questions/52679350/how-to-find-out-event-key-from-event-code

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