检测CAPS LOCK何时为ON

时间:2015-06-10 03:31:54

标签: javascript jquery html passwords capslock

我有这个代码用于向密码添加按键。如果 capslock 打开,它将触发。我是从How do you tell if caps lock is on using JavaScript?

得到的
$("input[type='password']").keypress(function(e) {

    var $warn = $(this).next(".capsWarn"); // handle the warning mssg
    var kc = e.which; //get keycode
    var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
    var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
    // event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
    var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed

    // uppercase w/out shift or lowercase with shift == caps lock
    if ( (isUp && !isShift) || (isLow && isShift) ) {
        $warn.show();
    } else {
        $warn.hide();
    }

}).after(capLock());
function capLock(e){
 alert('CAPSLOCK is ON');
}

原始代码的邮件位于span

...}).after(<span class='capsWarn error' style='display:none;'>CAPSLOCK is ON</span>);

我希望它是一条警报消息,但它没有像我预期的那样执行。在加载时,它应该提醒消息,但即使capslockon也会显示警告。

如何让它检测到密钥并显示警报?

1 个答案:

答案 0 :(得分:6)

$("input[type='password']").keypress(function(e) {

    var $warn = $(this).next(".capsWarn");//can be removed since you are just using alert
    var kc = e.which; //get keycode
    var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
    var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
    // event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
    var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed

    // uppercase w/out shift or lowercase with shift == caps lock
    if ( (isUp && !isShift) || (isLow && isShift) ) {
        capLock(); // alerts "CAPSLOCK is ON"
    }

});
function capLock() {
 alert('CAPSLOCK is ON');
}