Cancel the keydown in HTML

后端 未结 6 927
清歌不尽
清歌不尽 2020-11-29 10:28

How can I cancel the keydown of a specific key on the keyboard, for example(space, enter and arrows) in an HTML page.

6条回答
  •  心在旅途
    2020-11-29 10:48

    If you're only interested in the example keys you mentioned, the keydown event will do, except for older, pre-Blink versions of Opera (up to and including version 12, at least) where you'll need to cancel the keypress event. It's much easier to reliably identify non-printable keys in the keydown event than the keypress event, so the following uses a variable to set in the keydown handler to tell the keypress handler whether or not to suppress the default behaviour.

    var cancelKeypress = false;
    
    document.onkeydown = function(evt) {
        evt = evt || window.event;
        cancelKeypress = /^(13|32|37|38|39|40)$/.test("" + evt.keyCode);
        if (cancelKeypress) {
            return false;
        }
    };
    
    /* For Opera */
    document.onkeypress = function(evt) {
        if (cancelKeypress) {
            return false;
        }
    };
    

提交回复
热议问题