Cancel the keydown in HTML

后端 未结 6 921
清歌不尽
清歌不尽 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 11:00

    I only develop for IE because my works requires it, so there is my code for numeric field, not a beauty but works just fine

        $(document).ready(function () {
    
        $("input[class='numeric-field']").keydown(function (e) {
    
            if (e.shiftKey == 1) {
                return false
            }
    
            var code = e.which;
            var key;
    
            key = String.fromCharCode(code);
    
            //Keyboard numbers   
            if (code >= 48 && code <= 57) {
                return key;
            } //Keypad numbers
            else if (code >= 96 && code <= 105) {
                return key
            } //Negative sign
            else if (code == 189 || code == 109) {
                var inputID = this.id;
                var position = document.getElementById(inputID).selectionStart
                if (position == 0) {
                    return key
                }
                else {
                    e.preventDefault()
                }
            }// Decimal point
            else if (code == 110 || code == 190) {
                var inputID = this.id;
                var position = document.getElementById(inputID).selectionStart
    
                if (position == 0) {
                    e.preventDefault()
                }
                else {
                    return key;
                }
            }// 37 (Left Arrow), 39 (Right Arrow), 8 (Backspace) , 46 (Delete), 36 (Home), 35 (End)
            else if (code == 37 || code == 39 || code == 8 || code == 46 || code == 35 || code == 36) {
                return key
            }
            else {
                e.preventDefault()
            }
        });
    
    });
    

提交回复
热议问题