我需要检测事件keydown和keyup中字符的大小写
$('body').keydown(
    function(event) {
        var charCode = (event.which) ? event.which : event.keyCode;
        var char = String.fromCharCode(charCode);
        console.log(char + " is down pressed");
    }
);
$('body').keyup(
    function(event) {
        var charCode = (event.which) ? event.which : event.keyCode;
        var char = String.fromCharCode(charCode);
        console.log(char + " is up pressed");
    }
);你可以在这里尝试一下:http://jsfiddle.net/8dqwW/
即使没有按下大写锁定,它也总是返回大写字母。
在这两个事件中,如何检测按下大小写的字母?
发布于 2013-06-10 23:26:20
keyup和keydown无法检测大小写。
只有keypress可以做到这一点!
发布于 2018-02-19 03:34:50
使用event.key和现代JS!
不再有数字代码了。您可以直接检查key。例如"Enter"、"LeftArrow"、"r"或"R"。"keypress"、"keydown"或"keyup"都可以工作。
document.addEventListener("keypress", function (event) {
    const key = event.key;
    const keyLower = key.toLowerCase();
    // Check it is a char between A-Z, not numbers, etc.
    if (key.length !== 1 || keyLower < "a" || keyLower > "z") {
        return;
    }
    // Check for case
    const isUpperCase = (key !== keyLower);
});您可以使用正则表达式来简化它
const key = event.key;
const isLowerCaseLetter = (/[a-z]/.test(key));
const isUpperCaseLetter = (/[A-Z]/.test(key));发布于 2013-04-04 17:46:01
如果字符转换为大写后仍然相同,则从一开始就是大写的:
if (fromCharCode(e.which).toUpperCase() == fromCharCode(e.which))由于jQuery对e.which进行了规范化,而keypress事件的工作方式略有不同,因此我会这样做:
$('body').on({
    keypress: function(e) {
        var char = String.fromCharCode(e.which),
            isUpper = char == char.toUpperCase();
        console.log(char + ' is pressed' + (isUpper ? ' and uppercase' : ''))
    }
});https://stackoverflow.com/questions/15807715
复制相似问题