你如何告诉如果大写锁定使用JavaScript?

但有一个警告:我做了谷歌,我能找到的最好的解决方案是附加一个onkeypress事件到每个输入,然后检查每次按下的字母是否大写,如果是,然后检查shift是否也按下。如果不是,那么caps lock必须是打开的。这感觉真的很脏,而且…浪费——肯定有比这更好的办法吗?


当前回答

在jQuery中,

$('#example').keypress(function(e) { 
    var s = String.fromCharCode( e.which );
    if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
        alert('caps is on');
    }
});

避免类似退格键的错误,需要s. tolowercase () !== s。

其他回答

We use getModifierState to check for caps lock, it's only a member of a mouse or keyboard event so we cannot use an onfocus. The most common two ways that the password field will gain focus is with a click in or a tab. We use onclick to check for a mouse click within the input, and we use onkeyup to detect a tab from the previous input field. If the password field is the only field on the page and is auto-focused then the event will not happen until the first key is released, which is ok but not ideal, you really want caps lock tool tips to display once the password field gains focus, but for most cases this solution works like a charm.

HTML

<input type="password" id="password" onclick="checkCapsLock(event)" onkeyup="checkCapsLock(event)" />

JS

function checkCapsLock(e) {
  if (e.getModifierState("CapsLock")) {
    console.log("Caps");
  }
}

https://codepen.io/anon/pen/KxJwjq

这是一种解决方案,除了在写入时检查状态外,还在每次按下Caps Lock键时切换警告消息(有一些限制)。

它还支持A-Z范围之外的非英语字母,因为它根据toUpperCase()和toLowerCase()检查字符串字符,而不是根据字符范围检查。

$(function(){ //Initialize to hide caps-lock-warning $('.caps-lock-warning').hide(); //Sniff for Caps-Lock state $("#password").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)) { this.caps = true; // Enables to do something on Caps-Lock keypress $(this).next('.caps-lock-warning').show(); } else if((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey)|| (s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) { this.caps = false; // Enables to do something on Caps-Lock keypress $(this).next('.caps-lock-warning').hide(); }//else else do nothing if not a letter we can use to differentiate }); //Toggle warning message on Caps-Lock toggle (with some limitation) $(document).keydown(function(e){ if(e.which==20){ // Caps-Lock keypress var pass = document.getElementById("password"); if(typeof(pass.caps) === 'boolean'){ //State has been set to a known value by keypress pass.caps = !pass.caps; $(pass).next('.caps-lock-warning').toggle(pass.caps); } } }); //Disable on window lost focus (because we loose track of state) $(window).blur(function(e){ // If window is inactive, we have no control on the caps lock toggling // so better to re-set state var pass = document.getElementById("password"); if(typeof(pass.caps) === 'boolean'){ pass.caps = null; $(pass).next('.caps-lock-warning').hide(); } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="password" id="password" /> <span class="caps-lock-warning" title="Caps lock is on!">CAPS</span>

注意,只有在按下caps lock键之前知道caps lock的状态时,观察caps lock切换才有用。当前的大写锁定状态由密码元素上的caps JavaScript属性保持。这是当用户按下一个大写或小写字母时,我们第一次验证大写锁定状态时设置的。如果窗口失去焦点,我们就不能再观察到caps锁定切换,所以我们需要重置到未知状态。

Javascript代码

<script type="text/javascript">
   function isCapLockOn(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('alert').style.visibility = 'visible';
   else
       document.getElementById('alert').style.visibility = 'hidden';
   }
</script>

现在我们需要使用Html来关联这个脚本

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

Many existing answers will check for caps lock on when shift is not pressed but will not check for it if you press shift and get lowercase, or will check for that but will not also check for caps lock being off, or will check for that but will consider non-alpha keys as 'off'. Here is an adapted jQuery solution that will show a warning if an alpha key is pressed with caps (shift or no shift), will turn off the warning if an alpha key is pressed without caps, but will not turn the warning off or on when numbers or other keys are pressed.

$("#password").keypress(function(e) { 
    var s = String.fromCharCode( e.which );
    if ((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey)|| //caps is on
      (s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)) {
        $("#CapsWarn").show();
    } else if ((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey)||
      (s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) { //caps is off
        $("#CapsWarn").hide();
    } //else upper and lower are both same (i.e. not alpha key - so do not hide message if already on but do not turn on if alpha keys not hit yet)
  });

这是一个自定义的jquery插件,使用jquery ui,由这个页面上的所有好主意和工具提示小部件组成。大写锁定消息是自动应用于所有密码框,不需要更改您当前的html。

自定义插件代码…

(function ($) {
    $.fn.capsLockAlert = function () {
        return this.each(function () {
            var capsLockOn = false;
            var t = $(this);
            var updateStatus = function () {
                if (capsLockOn) {
                    t.tooltip('open');
                } else {
                    t.tooltip('close');
                }
            }
            t.tooltip({
                items: "input",
                position: { my: "left top", at: "left bottom+10" },
                open: function (event, ui) {
                    ui.tooltip.css({ "min-width": "100px", "white-space": "nowrap" }).addClass('ui-state-error');
                    if (!capsLockOn) t.tooltip('close');
                },
                content: function () {
                    return $('<p style="white-space: nowrap;"/>')
                        .append($('<span class="ui-icon ui-icon-alert" style="display: inline-block; margin-right: 5px; vertical-align: text-top;" />'))
                        .append('Caps Lock On');
                }
            })
            .off("mouseover mouseout")
            .keydown(function (e) {
                if (e.keyCode !== 20) return;
                capsLockOn = !capsLockOn;
                updateStatus();
            })
            .keypress(function (e) {
                var kc = e.which; //get keycode

                var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
                var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
                if (!isUp && !isLow) return; //This isn't a character effected by caps lock

                // 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)) {
                    capsLockOn = true;
                } else {
                    capsLockOn = false;
                }
                updateStatus();
            });
        });
    };
})(jQuery);

适用于所有密码元素…

$(function () {
    $(":password").capsLockAlert();
});