69

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

4

5 回答 5

109

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

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

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

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

代码:

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

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

解决方法keydown

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

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

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

下面的完整代码和更新的演示: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));
    });    
});

更多关于键盘事件——

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

keydown当用户按下某个键时触发。它在用户按住键时重复。

keypress当一个实际的字符被插入时触发,例如,一个文本输入。它在用户按住键时重复。

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

当第一次按下某个键时,将keydown发送事件。如果键不是修饰键,keypress则发送事件。当用户释放键时,keyup发送事件。

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

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

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

keyup,keydown vs keypress

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

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

参考:

  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

于 2012-10-29T18:29:47.343 回答
97

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

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

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

于 2010-02-08T08:09:19.323 回答
1

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

    $("input").on("keypress", function(e) {
        if(!jQuery.isNumeric(String.fromCharCode(e.which)))
            return false;
    });
于 2013-11-20T23:44:02.500 回答
1

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/

于 2016-08-18T07:39:11.670 回答
0

我创建并使用上面的 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;
        });
    }
};

例子,

<input type="text" data-mapkey="GR_EN" />
<script type="text/javascript">
    new CharMapper("body");
</script>
于 2017-05-24T13:17:35.493 回答