简体   繁体   English

检测CAPS LOCK何时为ON

[英]Detecting when CAPS LOCK is ON

I have this code for adding a keypress to a password. 我有这个代码用于将密钥添加到密码。 If capslock is on it will trigger. 如果封锁处于打开状态,则会触发。 I got it from How do you tell if caps lock is on using JavaScript? 我从如何判断是否使用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');
}

The original code has the message in a span : 原始代码包含span消息:

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

I wanted it to be an alert message but it is not performing as I expect it to. 我希望它是一个警报消息,但它没有像我期望的那样执行。 On load it should alert the message but even if the capslock is on it is not showing the alert. 在加载时,它应该警告消息,但即使capslock on它也不会显示警报。

How do I get it to detect the key and present the alert? 如何让它检测到密钥并显示警报?

$("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');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM