How to add onkeydown to body?

后端 未结 3 1358
离开以前
离开以前 2021-01-18 07:08

In my index.html I have this code. I would need to add onkeydown event to that body in Main.onLoad().

Any idea how to do it?



        
3条回答
  •  臣服心动
    2021-01-18 07:37

    In a Javascript block, try to use window.onkeydown (MDN).

    You can also use document.onkeydown and document.body.onkeydown.

    Here is an example for you:

    JavaScript

    document.body.onkeydown = function(e){
        alert(String.fromCharCode(e.keyCode)+" --> "+e.keyCode);
    };
    

    Live Demo

    The code above can be put in any valid JavaScript block (such as Main.onLoad() function).

提交回复
热议问题