keyup事件总是返回大写字母 [英] keyup event always return uppercase letter

查看:177
本文介绍了keyup事件总是返回大写字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试写一些类似于'占位符'polyfill的东西。我想在输入字段上捕获keyup事件并获取用户输入的char,所以我有这样的代码:

I'm trying to write something similar to a 'placeholder' polyfill. I would like to catch the keyup event on an input field and get the char the user entered, so i have this code:

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

});

问题是这总是返回按下的字符的大写版本,我怎么知道是否按下了char是大写还是小写?

The problem is this always returns an Uppercase version of the pressed char, how can i know if the pressed char was uppercase or lowercase?

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

I know keypress gives the pressed char but it does not activate on all keypress events (like backspace).

推荐答案

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

You can't easily get this information from keyup because keyup only knows which keys are being pressed, not which letters are being typed. You could check for the shift key being down and you could also try to track caps lock yourself, but if someone pressed it outside the browser, you'll end up getting the wrong case characters.

您可以尝试按键事件。虽然jQuery报告它并不总是表现出来相同的跨浏览器。来自doc:

You could try the keypress event., though jQuery reports it does not always behave the same cross-browser. From the doc:


请注意,keydown和keyup提供一个代码,指示按下
的键,而keypress指示哪个字符是进入。对于
的例子,小写的a将被keydown和keyup报告为65,
将被按键报告为97。所有
事件报告大写A为65。由于这种区别,当捕获特殊键击
(如箭头键)时,.keydown()或.keyup()是更好的选择。

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.

这篇关于keyup事件总是返回大写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆