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

发布于 2024-08-20 19:11:58 字数 142 浏览 9 评论 0原文

我需要找出从 jQuery 的 keydown 函数调用的处理程序中将哪个字符输入到文本字段中。 key.which 只给我键码,但我需要找出 key 代表哪个 ASCII 字符。我该怎么做?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

陪我终i 2024-08-27 19:11:58

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

keydownkeyup 提供指示按下哪个键的代码,而 keypress 指示输入哪个字符。

使用 jQuery e.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 上工作。解决方法是使用 key 创建一个对象作为没有 Shift 键的 charCode,并且该值是带有 Shift 键的。

注意:如 @Sajjan Sarkar指出不同浏览器返回的e.which键码值存在一些差异。 在此处了解更多信息

更新了演示代码以标准化跨浏览器 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

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

keyup、keydown 与 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

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

keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered.

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

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

Code:

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

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

Workaround for 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.

Note: As @Sajjan Sarkar pointed out there are some differences in e.which keycode value returned from different browser. Read more here

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

Full Code below and updated DEMO: 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 Fires when the user depresses a key. It repeats while the user keeps the key depressed.

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

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

When a key is first depressed, the keydown event is sent. If the key is not a modifier key, the keypress event is sent. When the user releases the key, the keyup event is sent.

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/

keyup, keydown vs keypress

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

DEMO: 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

謸气贵蔟 2024-08-27 19:11:58

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

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

请记住,对于 keydown()keyup(),您必须使用 e.shiftKey 状态来跟踪大小写。

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.

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.shiftKey state.

情归归情 2024-08-27 19:11:58

我做这个。如果该值不是数字,它将忽略按键。
看起来工作没有任何问题......

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

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;
    });
z祗昰~ 2024-08-27 19:11:58

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/

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

 $(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/

土豪 2024-08-27 19:11:58

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

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.

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>
静赏你的温柔 2024-08-27 19:11:58

keypress 已被弃用,您应该使用 keydown 代替

使用 .key - 获取 keypress

语法为:

$(selector).keydown(function(event) {
  console.log(event.key)
})

示例:

$(document).keydown(function(event) {
  // print out each keypress
  console.log(event.key)
})

keypress is deprecated, you should use keydown instead

Use .key - to get the keypress

The syntax is:

$(selector).keydown(function(event) {
  console.log(event.key)
})

Example:

$(document).keydown(function(event) {
  // print out each keypress
  console.log(event.key)
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文