How to take keyboard input in JavaScript?

前端 未结 5 2040
醉梦人生
醉梦人生 2020-12-02 08:50

I want to take keyboard input in JavaScript, where arrow keys, when pressed, will result in the change in shape of a particular shape. How do I take the input of any of the

5条回答
  •  鱼传尺愫
    2020-12-02 09:29

    Since event.keyCode is deprecated, I found the event.key useful in javascript. Below is an example for getting the names of the keyboard keys pressed (using an input element). They are given as a KeyboardEvent key text property:

    function setMyKeyDownListener() {
        window.addEventListener(
          "keydown",
          function(event) {MyFunction(event.key)}
        )
    }
    
    function MyFunction (the_Key) {
        alert("Key pressed is: "+the_Key);
    }
    html { font-size: 4vw; background-color: green; color: white; padding: 1em; }
    
        

提交回复
热议问题