编程语言
首页 > 编程语言> > javascript – 在“onfocus”事件中检查CapsLock ON

javascript – 在“onfocus”事件中检查CapsLock ON

作者:互联网

用于检查Capslock是否打开的以下代码在“onkeypress”事件上正常工作.

但我希望它用于“onfocus”活动.
 我尝试用“onfocus”替换“onkeypress”用于控件,但它对我不起作用.

有帮助吗? (在javascriptJquery中)

 <script type="text/javascript" language="Javascript">
    function capLock(e) {
        kc = e.keyCode ? e.keyCode : e.which;
        sk = e.shiftKey ? e.shiftKey : ((kc == 16) ? true : false);
        if (((kc >= 65 && kc <= 90) && !sk) || ((kc >= 97 && kc <= 122) && sk))
            document.getElementById('divMayus').style.visibility = 'visible';
        else
            document.getElementById('divMayus').style.visibility = 'hidden';
    }
</script>

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

解决方法:

有一个名为capslockstate的jQuery插件,它将跟踪大写锁定键的状态,允许您在需要时使用该信息.

它将监视整个页面的状态,然后您可以在所需元素获得焦点时检索状态.

它也基于观看按键,但不限于较低的ASCII字符,并处理按下Caps Lock键本身的情况.

你的情况会变成:

<script src="{path-to}/jquery-capslockstate.js"></script>
<script>
    $(document).ready(function() {
        $(window).capslockstate();

        $(window).bind("capsOn", function(event) {
            if ($("#txtPassword:focus").length > 0) {
                document.getElementById('divMayus').style.visibility = 'visible';
            }
        });
        $(window).bind("capsOff capsUnknown", function(event) {
            document.getElementById('divMayus').style.visibility = 'hidden';
        });
        $("#txtPassword").bind("focusout", function(event) {
            document.getElementById('divMayus').style.visibility = 'hidden';
        });
        $("#txtPassword").bind("focusin", function(event) {
            if ($(window).capslockstate("state") === true) {
                document.getElementById('divMayus').style.visibility = 'visible';
            }
        });
    });
</script>

<input type="text" name="txtuname" />
<input type="password" name="txtPassword" id="txtPassword" />
<div id="divMayus" style="visibility:hidden">Caps Lock is on.</div>

请注意,我只是jQueryified基本位,仍然可以做更多.

标签:key-events,javascript,jquery,onfocus
来源: https://codeday.me/bug/20190826/1727436.html