Detect caps lock on/off using jQuery [duplicate]

戏子无情 提交于 2019-11-26 22:40:24

问题


How can I detect the Caps Lock key on/off using jQuery? I have a password textbox, and I allow only lowercase letters so I don't want the Caps Lock key to be on.

Is it possible to detect the state of Caps Lock key using jQuery?


回答1:


How to detect Caps Lock with Javascript.

function capLock(e){
  var kc = e.keyCode ? e.keyCode : e.which;
  var sk = e.shiftKey ? e.shiftKey : kc === 16;
  var visibility = ((kc >= 65 && kc <= 90) && !sk) || 
      ((kc >= 97 && kc <= 122) && sk) ? 'visible' : 'hidden';
  document.getElementById('divMayus').style.visibility = visibility
}

Then for your password form:

<input type="password" name="txtPassword" onkeypress="capLock(event)" />
<div id="divMayus" style="visibility:hidden">Caps Lock is on.</div> 



回答2:


There is a jQuery plugin called capslockstate that will monitor the state of the caps lock key over the entire page, not just in specific fields.

You can either query the state of the caps lock key or define event listeners to react to state changes.

The plugin does a better job of detection and state management than the other suggestions here, including working with non-English keyboards, monitoring the use of the Caps Lock key itself, and not forgetting the state if non alpha characters are typed.

There are two demos, one showing basic event binding and another showing the warning only when the password field has focus.

e.g.

$(document).ready(function() {

    /* 
    * Bind to capslockstate events and update display based on state 
    */
    $(window).bind("capsOn", function(event) {
        $("#statetext").html("on");
    });
    $(window).bind("capsOff", function(event) {
        $("#statetext").html("off");
    });
    $(window).bind("capsUnknown", function(event) {
        $("#statetext").html("unknown");
    });

    /*
    * Additional event notifying there has been a change, but not the state
    */
    $(window).bind("capsChanged", function(event) {
        $("#changetext").html("changed").show().fadeOut();
    });

    /* 
    * Initialize the capslockstate plugin.
    * Monitoring is happening at the window level.
    */
    $(window).capslockstate();

    // Call the "state" method to retreive the state at page load
    var initialState = $(window).capslockstate("state");
    $("#statetext").html(initialState);

});

and

$(document).ready(function() {

    /* 
    * Bind to capslockstate events and update display based on state 
    */
    $(window).bind("capsOn", function(event) {
        if ($("#Passwd:focus").length > 0) {
            $("#capsWarning").show();
        }
    });
    $(window).bind("capsOff capsUnknown", function(event) {
        $("#capsWarning").hide();
    });
    $("#Passwd").bind("focusout", function(event) {
        $("#capsWarning").hide();
    });
    $("#Passwd").bind("focusin", function(event) {
        if ($(window).capslockstate("state") === true) {
            $("#capsWarning").show();
        }
    });

    /* 
    * Initialize the capslockstate plugin.
    * Monitoring is happening at the window level.
    */
    $(window).capslockstate();

});

The code for the plugin is viewable on GitHub.




回答3:


But you forgot something. If you press capslock and shift and type, there won't be the message 'caps is on'.

Here is a corrected version:

<html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <script language="Javascript">
        $(document).ready(function(){
            $('input').keypress(function(e) { 
                var s = String.fromCharCode( e.which );

                if((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) ||
                   (s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)){
                    if($('#capsalert').length < 1) $(this).after('<b id="capsalert">CapsLock is on!</b>');
                } else {
                    if($('#capsalert').length > 0 ) $('#capsalert').remove();
                }
            });
        });
    </script>
</head>
<body>
    <label style="float:left;display:block;width:80px;">Login:</label><input type="text" /><br />
    <label style="float:left;display:block;width:80px;">Password:</label><input type="password" /><br />
</body>




回答4:


I found a better way to do this using jquery: this way you can detect when the user press capslock, the user doesn't need to type a letter to check: (the user needs to type at least 1 key to start detecting the capslock) demo: http://arthurfragoso.onphp.net/codes/capslock.html

<html><head><title>Checking Caps Lock using Jquery - Javascript</title></head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<form action="/codes/capslock.html" id="formid"> 

            <div>
                User:
            </div>
            <div>
                <input type="text" id="user" />
            </div>

            <div>
                Password:
            </div>
            <div>
                <input type="password" id="password" />
            </div>

            <div id="capslockdiv" style="display: none; color: red;">
                Caps Lock On
            </div>

        <div>
                <input type="submit" />
            </div>
</form>
<script>
 $(document).ready(
    function () {
        check_capslock_form($('#formid')); //applies the capslock check to all input tags
    }
 );

document.onkeydown = function (e) { //check if capslock key was pressed in the whole window
    e = e || event;
    if (typeof (window.lastpress) === 'undefined') { window.lastpress = e.timeStamp; }
    if (typeof (window.capsLockEnabled) !== 'undefined') {
        if (e.keyCode == 20 && e.timeStamp > window.lastpress + 50) {
            window.capsLockEnabled = !window.capsLockEnabled;
            $('#capslockdiv').toggle();
        }
        window.lastpress = e.timeStamp;
        //sometimes this function is called twice when pressing capslock once, so I use the timeStamp to fix the problem
    }

};

function check_capslock(e) { //check what key was pressed in the form
    var s = String.fromCharCode(e.keyCode);
    if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
        window.capsLockEnabled = true;
        $('#capslockdiv').show();
    }
    else {
        window.capsLockEnabled = false;
        $('#capslockdiv').hide();
    }
}

function check_capslock_form(where) {
    if (!where) { where = $(document); }
    where.find('input,select').each(function () {
        if (this.type != "hidden") {
            $(this).keypress(check_capslock);
        }
    });
}
</script>

</body>
</html>



回答5:


What I do is put up a warning when

  1. the username or password is incorrect and
  2. the username or password provided was all upper-case.

It's a pretty bad idea to only allow smaller letters. You're cutting down the number of possible passwords by a tremendous amount by doing that.




回答6:


After the user has created their password, when they’re entering it during login, you could just convert it to lowercase on the server before checking whether it’s correct.

Saves effort for the user that way.



来源:https://stackoverflow.com/questions/2308895/detect-caps-lock-on-off-using-jquery

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