In Javascript, How to detect the character case (upper/lower) in keydown & keyup events?

隐身守侯 提交于 2019-12-12 16:16:08

问题


I need to detect the case of characters in event keydown and 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");
    }
);

You may try it here: http://jsfiddle.net/8dqwW/
It's always returning the upper case letter even if no caps lock is pressed.

How can I detect the letter pressed with its case, either upper or lower in those two events ?


回答1:


keyup and keydown cannot detect the upper/lower case.
Only keypress can do so !




回答2:


If the character is still the same after converting it to uppercase, it was uppercase to begin with :

if (fromCharCode(e.which).toUpperCase() == fromCharCode(e.which))

As jQuery normalizes e.which, and the keypress event works a little differently, I'd do something like :

$('body').on({
    keypress: function(e) {
        var char = String.fromCharCode(e.which),
            isUpper = char == char.toUpperCase();
        console.log(char + ' is pressed' + (isUpper ? ' and uppercase' : ''))
    }
});

FIDDLE




回答3:


Use event.key and modern JS!

No number codes anymore. You can check key directly. For example "Enter", "LeftArrow", "r", or "R". "keypress", "keydown", or "keyup" will all work.

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);
});

You could simplify it with a regex

const key = event.key;
const isLowerCaseLetter = (/[a-z]/.test(key));
const isUpperCaseLetter = (/[A-Z]/.test(key));


来源:https://stackoverflow.com/questions/15807715/in-javascript-how-to-detect-the-character-case-upper-lower-in-keydown-keyup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!