使用 jQuery 检测大写锁定开/关

发布于 2024-08-22 09:04:54 字数 135 浏览 8 评论 0原文

如何使用 jQuery 检测 Caps Lock 键的开/关?我有一个密码文本框,并且只允许使用小写字母,因此我不希望打开 Caps Lock 键。

是否可以使用 jQuery 检测 Caps Lock 键的状态?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

辞别 2024-08-29 09:04:54

如何使用 Javascript 检测 Caps Lock。

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
}

然后输入您的密码表单:

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

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> 
几度春秋 2024-08-29 09:04:54

有一个名为 capslockstate 的 jQuery 插件,它将监视大写锁定键的状态整个页面,而不仅仅是特定字段。

您可以查询大写锁定键的状态或定义事件侦听器以对状态更改做出反应。

与此处的其他建议相比,该插件在检测和状态管理方面做得更好,包括使用非英语键盘、监视 Caps Lock 键本身的使用,以及在键入非字母字符时不会忘记状态。

有两个演示,一个显示基本事件绑定,另一个仅当密码字段具有焦点时才显示警告

例如

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

});

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

});

插件的代码可以在 GitHub 上查看。

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.

向日葵 2024-08-29 09:04:54

但你忘记了一些事情。如果您按 CapsLock 和 Shift 键并键入,则不会出现“Caps is on”消息。

这是一个更正的版本:

<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>

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>

苍景流年 2024-08-29 09:04:54

我找到了一个更好的方法来使用jquery来做到这一点:这样你就可以检测用户何时按下大写锁定,用户不需要输入字母来检查:(用户需要输入至少1个键来开始检测大写锁定)
演示: 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>

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>
〗斷ホ乔殘χμё〖 2024-08-29 09:04:54

发出警告

  1. 我所做的是当用户名或密码不正确并且
  2. 提供的用户名或密码全部大写时

。只允许使用较小的字母是一个非常糟糕的主意。通过这样做,您将大大减少可能的密码数量。

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.

梦罢 2024-08-29 09:04:54

用户创建密码后,当他们在登录期间输入密码时,您可以在服务器上将其转换为小写,然后再检查密码是否正确。

这样可以为用户节省精力。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文