Detect printable keys

前端 未结 2 1545
不知归路
不知归路 2020-12-09 09:33

I need to detect whether the key which has just been pressed is a printable key, like a character, possibly accented, a number, a space, a punctuation symbol and so on, or a

2条回答
  •  盖世英雄少女心
    2020-12-09 09:58

    I answered a similar question yesterday. Note that you have to use the keypress event for anything character-related; keydown won't do.

    I would argue that Enter is printable, by the way, and this function considers it to be. If you disagree, you can amend it to filter out keypresses with the which or keyCode property of the event set to 13.

    function isCharacterKeyPress(evt) {
        if (typeof evt.which == "undefined") {
            // This is IE, which only fires keypress events for printable keys
            return true;
        } else if (typeof evt.which == "number" && evt.which > 0) {
            // In other browsers except old versions of WebKit, evt.which is
            // only greater than zero if the keypress is a printable key.
            // We need to filter out backspace and ctrl/alt/meta key combinations
            return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
        }
        return false;
    }
    
    var input = document.getElementById("your_input_id");
    input.onkeypress = function(evt) {
        evt = evt || window.event;
    
        if (isCharacterKeyPress(evt)) {
            // Do your stuff here
            alert("Character!");
        }
    });
    

提交回复
热议问题