使用jQuery检测大写锁定键的开启/关闭

25

如何使用jQuery检测大写锁定键是否开启?我有一个密码文本框,我只允许小写字母,因此不希望大写锁定键处于开启状态。

是否可以使用jQuery检测大写锁定键的状态?

6个回答

34

如何使用 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
}

那么对于你的密码表单:

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

@twodayslate +1 有价值的回答...但我正在寻找jQuery。 - ACP
13
+1,但是为什么要把kcsk作为全局变量?你应该在函数内部使用var来声明它们。另外,(kc == 16)已经是一个布尔表达式了,你不需要用((kc == 16)?true:false)来包裹它。 - Keith
+1 非常好,对我很有帮助,谢谢... :) - abhi

15

有一个jQuery插件叫做capslockstate,它可以监测整个页面而不仅仅是特定区域的大写锁定键状态。

你可以查询大写锁定键状态或定义事件监听器以响应状态更改。

该插件比这里的其他建议在检测和状态管理方面做得更好,包括与非英语键盘一起工作、监视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上查看。


这是最完整和可扩展的答案。 - BallisticPugh

8

但是你忘了一件事。如果你按下大写锁定键和shift键并输入,就不会出现“大写锁定已开启”的消息。

这是一个更正的版本:

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


这对我没有起作用。我使用了“e.key”而不是“e.which”,它正常工作了。为了背景,我在Mac上使用Chrome。 - CallSign-Filter

3
我发现使用jquery有更好的方法来实现这个功能:通过这种方式,您可以检测到用户何时按下大写锁定键,而不需要输入字母进行检查(用户需要至少输入一个键才能开始检测大写锁定键)。示例演示页面: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>

1

我的做法是在以下情况下发出警告:

  1. 用户名或密码不正确
  2. 提供的用户名或密码全部为大写字母。

仅允许小写字母是一个非常糟糕的想法。这样做会大大减少可能的密码数量。


-8

用户创建密码后,在登录时输入密码时,您可以在检查其是否正确之前在服务器上将其转换为小写。

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


5
我认为您不应更改用户提交的密码 - 一个强密码将包含大写字母和小写字母的混合。 - Chris Edwards

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接