gpt4 book ai didi

javascript - keyup 事件总是返回大写字母

转载 作者:行者123 更新时间:2023-12-03 21:48:26 25 4
gpt4 key购买 nike

我正在尝试编写类似于“占位符”polyfill 的内容。我想捕获输入字段上的 keyup 事件并获取用户输入的字符,所以我有以下代码:

 $elem.on('keyup',function(e){  
var $this = $(this),
val = $this.val(),
code = (e.keyCode ? e.keyCode : e.which);
console.log(String.fromCharCode(code));

});

问题是这总是返回按下的字符的大写版本,我如何知道按下的字符是大写还是小写?

我知道keypress给出了按下的字符,但它不会在所有按键事件(如退格键)上激活。

最佳答案

您无法轻松地从 keyup 获取此信息,因为 keyup 只知道按下了哪些键,而不知道正在键入哪些字母。您可以检查是否按下了 Shift 键,也可以尝试自己跟踪大写锁定,但如果有人在浏览器外按下它,您最终会得到错误的大小写字符。

您可以尝试keypress event. ,尽管 jQuery 报告它并不总是具有相同的跨浏览器行为。来自文档:

Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.

关于javascript - keyup 事件总是返回大写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12568494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com