如何解码从 jQuery 的 keydown() 的事件处理程序按下的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2220196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:02:42  来源:igfitidea点击:

How to decode character pressed from jQuery's keydown()'s event handler

jqueryevent-handlingcharacterkeydown

提问by Chetan

I need to figure out which character was typed into a text field from within the handler that is called by jQuery's keydownfunction. key.whichgives me only the keycode, but I need to figure out which ASCII character keyrepresents. How do I do this?

我需要弄清楚哪个字符是从 jQuerykeydown函数调用的处理程序中输入到文本字段中的。key.which只给我键码,但我需要弄清楚哪个 ASCII 字符key代表。我该怎么做呢?

回答by Selvakumar Arumugam

The keyPressevent is what you need to get which character was entered. (See below workaround for keydown event).

keyPress事件是您获取输入的字符所需要的。(请参阅下面的 keydown 事件解决方法)。

keydownand keyupprovide a code indicating which key is pressed, while keypressindicates which character was entered.

keydownkeyup提供一个代码,指示按下了哪个键,同时keypress指示输入了哪个字符。

Using jQuery e.whichyou can get the key code and using String.fromCharCodeyou can get the specific character that was pressed (including shiftKey).

使用 jQuerye.which您可以获得关键代码,使用String.fromCharCode您可以获得按下的特定字符(包括shiftKey)。

DEMO:http://jsfiddle.net/9TyzP/3

演示:http : //jsfiddle.net/9TyzP/3

Code:

代码:

element.on ('keypress', function (e) {
    console.log(String.fromCharCode(e.which));
})

Note I said jQuery's e.whichbecause different browsers use differing properties to store this information. jQuery normalizes the .whichproperty so you can reliably use it to retrieve the key code.

注意我说 jQuery 是e.which因为不同的浏览器使用不同的属性来存储这些信息。jQuery 对.which属性进行了规范化,因此您可以可靠地使用它来检索关键代码。

Workaround for keydown

解决方法 keydown

However you can write a simple workaround to get the pressed character working on keydown.. The workaround is to create an object with key as the charCode without shift keypress and the value is with shift key.

但是,您可以编写一个简单的解决方法来让按下的字符在keydown.. 上工作。解决方法是创建一个带有键作为 charCode 的对象,而不使用 shift 按键,而值是使用 shift 键。

Note: As @Sajjan Sarkarpointed out there are some differences in e.whichkeycode value returned from different browser. Read more here

注意:正如@Sajjan Sarkar指出的那样e.which,不同浏览器返回的键码值存在一些差异。在这里阅读更多

Updated the DEMO code to normalize the cross browser keyCode value. Tested and verified in IE 8, FF and Chrome.

更新了演示代码以规范跨浏览器的 keyCode 值。在 IE 8、FF 和 Chrome 中测试和验证。

Full Code below and updated DEMO:http://jsfiddle.net/S2dyB/17/

下面的完整代码和更新的演示:http : //jsfiddle.net/S2dyB/17/

$(function() {

    var _to_ascii = {
        '188': '44',
        '109': '45',
        '190': '46',
        '191': '47',
        '192': '96',
        '220': '92',
        '222': '39',
        '221': '93',
        '219': '91',
        '173': '45',
        '187': '61', //IE Key codes
        '186': '59', //IE Key codes
        '189': '45'  //IE Key codes
    }

    var shiftUps = {
        "96": "~",
        "49": "!",
        "50": "@",
        "51": "#",
        "52": "$",
        "53": "%",
        "54": "^",
        "55": "&",
        "56": "*",
        "57": "(",
        "48": ")",
        "45": "_",
        "61": "+",
        "91": "{",
        "93": "}",
        "92": "|",
        "59": ":",
        "39": "\"",
        "44": "<",
        "46": ">",
        "47": "?"
    };

    $(element).on('keydown', function(e) {
        var c = e.which;

        //normalize keyCode 
        if (_to_ascii.hasOwnProperty(c)) {
            c = _to_ascii[c];
        }

        if (!e.shiftKey && (c >= 65 && c <= 90)) {
            c = String.fromCharCode(c + 32);
        } else if (e.shiftKey && shiftUps.hasOwnProperty(c)) {
            //get shifted keyCode value
            c = shiftUps[c];
        } else {
            c = String.fromCharCode(c);
        }

        //$(element).val(c);
    }).on('keypress', function(e) {
        //$(element).val(String.fromCharCode(e.which));
    });    
});

More about keyboard events --

更多关于键盘事件——

The keydown, keypress and keyup events fire when the user presses a key.

keydown、keypress 和 keyup 事件在用户按下某个键时触发。

keydownFires when the user depresses a key. It repeats while the user keeps the key depressed.

keydown当用户按下一个键时触发。当用户保持按键按下时它会重复。

keypressFires when an actual character is being inserted in, for instance, a text input. It repeats while the user keeps the key depressed.

keypress在插入实际字符时触发,例如,文本输入。当用户保持按键按下时它会重复。

keyupFires when the user releases a key, after the default action of that key has been performed.

keyup当用户释放一个键时触发,在该键的默认操作已经执行之后。

When a key is first depressed, the keydownevent is sent. If the key is not a modifier key, the keypressevent is sent. When the user releases the key, the keyupevent is sent.

当一个键被第一次按下时,keydown事件被发送。如果键不是修饰键,keypress则发送事件。当用户松开按键时,keyup事件被发送。

When a key is pressed and held down, it begins to auto-repeat. This results in a sequence of events similar to the following being dispatched:

当一个键被按下并按住时,它开始自动重复。这会导致发送类似于以下内容的一系列事件:

keydown
keypress
keydown
keypress
<<repeating until the user releases the key>>
keyup

DEMO:http://jsfiddle.net/9TyzP/1/

演示:http : //jsfiddle.net/9TyzP/1/

keyup, keydown vs keypress

按键,按键与按键

The keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed.

keydown 和 keyup 事件表示按键被按下或释放,而 keypress 事件表示正在输入一个字符。

DEMO:http://jsfiddle.net/9TyzP/

演示:http : //jsfiddle.net/9TyzP/

References:

参考:

  1. https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent

  2. http://www.quirksmode.org/dom/events/keys.html

  3. http://unixpapa.com/js/key.html

  1. https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent

  2. http://www.quirksmode.org/dom/events/keys.html

  3. http://unixpapa.com/js/key.html

回答by Max Shawabkeh

For character input, it is suggested you use keypress(), which will report the actual ASCII code for the character pressed. It automatically takes care of letter case, and ignores non-character presses. In either case, you can use fromCharCode() to convert to a string representation. E.g.

对于字符输入,建议您使用keypress(),它将报告按下字符的实际 ASCII 代码。它会自动处理字母大小写,并忽略非字符按下。无论哪种情况,您都可以使用 fromCharCode() 转换为字符串表示形式。例如

var c = String.fromCharCode(e.which) // or e.keyCode

Just remember that for keydown()and keyup(), you'll have to keep track of the case using the e.shiftKeystate.

请记住,对于keydown()and keyup(),您必须使用e.shiftKey状态跟踪案例。

回答by Christoffer

I do this. It will just ignore the keypress if the value is not a number. Seems to work without any problems...

我这样做。如果值不是数字,它只会忽略按键。似乎工作没有任何问题......

    $("input").on("keypress", function(e) {
        if(!jQuery.isNumeric(String.fromCharCode(e.which)))
            return false;
    });

回答by rexwolf

Selvakumar Arumugam's answer works like a charm for me...until I test numpad. So a minor update here:

Selvakumar Arumugam 的回答对我来说就像一个魅力......直到我测试数字键盘。所以这里有一个小更新:

 $(document).on('keydown', function(e) {
    var c = e.which;

    if (_to_ascii.hasOwnProperty(c)) {
        c = _to_ascii[c];
    }

    if (!e.shiftKey && (c >= 65 && c <= 90)) {
        c = String.fromCharCode(c + 32);
    } else if (e.shiftKey && shiftUps.hasOwnProperty(c)) {
        c = shiftUps[c];
    } else if (96 <= c && c <= 105) {
        c = String.fromCharCode(c - 48);
    }else {
        c = String.fromCharCode(c);
    }

    $kd.val(c);
})

http://jsfiddle.net/S2dyB/78/

http://jsfiddle.net/S2dyB/78/

回答by George Siggouroglou

I created and use the above javascript class for converting gr to en characters. It is able to be used for more languages. It uses JQuery for changing the value pressed from user.

我创建并使用上面的 javascript 类将 gr 转换为 en 字符。它能够用于更多语言。它使用 JQuery 来更改用户按下的值。

var CharMapper = function (selector) {
    this.getLanguageMapper = function (languageSource, languageTarget) {
        // Check if the map is already defined.
        if (typeof langugageCharMap === "undefined") {
            langugageCharMap = {};
        }
        if (typeof langugageCharMap[languageSource] === "undefined") {
            langugageCharMap[languageSource] = {};
        }

        // Initialize or get the language mapper.
        if (typeof langugageCharMap[languageSource][languageTarget] === "undefined") {
            switch (languageSource) {
                case "GR":
                    switch (languageTarget) {
                        case "EN":
                            langugageCharMap[languageSource][languageTarget] = {
                                "α": "a", "?": "a", "β": "b", "γ": "g", "δ": "d", "ε": "e", "?": "e", "ζ": "z", "η": "h", "?": "h", "θ": "th", "ι": "i", "?": "i", "?": "i", "?": "i", "κ": "k", "λ": "l", "μ": "m", "ν": "n", "ξ": "ks", "ο": "o", "?": "o", "π": "p", "ρ": "r", "σ": "s", "?": "s", "τ": "t", "υ": "y", "?": "y", "?": "y", "?": "y", "φ": "f", "χ": "x", "ψ": "ps", "ω": "o", "?": "o", "Α": "A", "?": "A", "Β": "B", "Γ": "G", "Δ": "D", "Ε": "E", "?": "E", "Ζ": "Z", "Η": "H", "?": "H", "Θ": "TH", "Ι": "I", "?": "I", "?": "I", "Κ": "K", "Λ": "L", "Μ": "M", "Ν": "N", "Ξ": "KS", "Ο": "O", "?": "O", "Π": "P", "Ρ": "R", "Σ": "S", "Τ": "T", "Υ": "Y", "?": "Y", "?": "Y", "Φ": "F", "Χ": "X", "Ψ": "PS", "Ω": "O", "?": "O"
                            };
                            break;
                        case "GR":
                        default:
                            throw "Language(" + languageTarget + ") is not supported as target for Language(" + languageSource + ").";
                    }
                    break;
                case "EN":
                default:
                    throw "Language(" + languageSource + ") is not supported as source.";
            }
        }

        return langugageCharMap[languageSource][languageTarget];
    };
    // Check the existance of the attribute.
    var items = $(selector).find("*[data-mapkey]");
    if (items.length === 0) {
        return;
    }

    // For each item.
    for (var i = 0; i < items.length; i++) {
        var item = items[i];

        // Get the source and target language.
        var languages = $(item).attr("data-mapkey");
        var languageSource = languages.split("_")[0];
        var languageTarget = languages.split("_")[1];

        // Add the event listener.
        var self = this;
        $(item).keypress(function (event) {
            event.stopPropagation();
            // Get the mapper to use.
            var mapper = self.getLanguageMapper(languageSource, languageTarget);
            // Get the key pressed.
            var keyPressed = String.fromCharCode(event.which);
            // Get the key to set. In case it doesn't exist in the mapper, get the key pressed.
            var keyToSet = mapper[keyPressed] || keyPressed;
            // Set the key to the dom.
            this.value = this.value + keyToSet;

            // Do not propagate.
            return false;
        });
    }
};

Example,

例子,

<input type="text" data-mapkey="GR_EN" />
<script type="text/javascript">
    new CharMapper("body");
</script>