How to take keyboard input in JavaScript?

前端 未结 5 2017
醉梦人生
醉梦人生 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:30

    You can do this by registering an event handler on the document or any element you want to observe keystrokes on and examine the key related properties of the event object.

    Example that works in FF and Webkit-based browsers:

    document.addEventListener('keydown', function(event) {
        if(event.keyCode == 37) {
            alert('Left was pressed');
        }
        else if(event.keyCode == 39) {
            alert('Right was pressed');
        }
    });
    

    DEMO

提交回复
热议问题