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

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


当前回答

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

其他回答

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> 

您可以使用KeyboardEvent来检测许多按键,包括最新浏览器上的大写锁。

getModifierState函数将提供以下状态:

Alt AltGraph 大写锁定 控制 Fn (Android) 元 时键盘上的数字 操作系统(Windows & Linux) ScrollLock 转变

这个演示工作在所有主要的浏览器,包括移动(caniuse)。

passwordField.addEventListener( 'keydown', function( event ) {
  var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
  console.log( caps ); // true when you press the keyboard CapsLock key
});

这是一种解决方案,除了在写入时检查状态外,还在每次按下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锁定切换,所以我们需要重置到未知状态。

还有另一个版本,清晰而简单,处理移位的capsLock,并且不受ascii限制,我认为:

document.onkeypress = function (e)
{
    e = e || window.event;
    if (e.charCode === 0 || e.ctrlKey || document.onkeypress.punctuation.indexOf(e.charCode) >= 0)
        return;
    var s = String.fromCharCode(e.charCode); // or e.keyCode for compatibility, but then have to handle MORE non-character keys
    var s2 = e.shiftKey ? s.toUpperCase() : s.toLowerCase();
    var capsLockOn = (s2 !== s);
    document.getElementById('capslockWarning').style.display = capsLockOn ? '' : 'none';
}
document.onkeypress.punctuation = [33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,91,92,93,94,95,96,123,124,125,126];

编辑:意义上的capsLockOn被逆转,多,固定。

编辑#2:在进一步检查之后,我做了一些更改,不幸的是,代码更详细了一些,但它可以适当地处理更多的操作。

Using e.charCode instead of e.keyCode and checking for 0 values skips a lot of non-character keypresses, without coding anything specific to a given language or charset. From my understanding, it's slightly less compatible, so older, non-mainstream, or mobile browsers may not behave as this code expects, but it's worth it, for my situation anyway. Checking against a list of known punctuation codes prevents them from being seen as false negatives, since they're not affected by caps lock. Without this, the caps lock indicator gets hidden when you type any of those punctuation characters. By specifying an excluded set, rather than an included one, it should be more compatible with extended characters. This is the ugliest, special-casiest bit, and there's some chance that non-Western languages have different enough punctuation and/or punctuation codes to be a problem, but again it's worth it IMO, at least for my situation.

jQuery与twitter引导

检查以下字符的大写锁定:

uppercase a - z前'Ä','Ö','Ü',' !', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';', '*', '''

小写字母a-Z或0-9或'ä', 'ö', 'ü', '。',', ',' +', '#'

/* check for CAPS LOCK on all password fields */
$("input[type='password']").keypress(function(e) {
    var kc = e.which; // get keycode

    var isUpperCase = ((kc >= 65 && kc <= 90) || (kc >= 33 && kc <= 34) || (kc >= 36 && kc <= 39) || (kc >= 40 && kc <= 42) || kc == 47 || (kc >= 58 && kc <= 59) || kc == 61 || kc == 63 || kc == 167 || kc == 196 || kc == 214 || kc == 220) ? true : false; // uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';'
    var isLowerCase = ((kc >= 97 && kc <= 122) || (kc >= 48 && kc <= 57) || kc == 35 || (kc >= 43 && kc <= 44) || kc == 46 || kc == 228 || kc == 223 || kc == 246 || kc == 252) ? true : false; // lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ','

    // 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 ((isUpperCase && !isShift) || (isLowerCase && isShift)) {
        $(this).next('.form-control-feedback').show().parent().addClass('has-warning has-feedback').next(".capsWarn").show();
    } else {
        $(this).next('.form-control-feedback').hide().parent().removeClass('has-warning has-feedback').next(".capsWarn").hide();
    }
}).after('<span class="glyphicon glyphicon-warning-sign form-control-feedback" style="display:none;"></span>').parent().after("<span class='capsWarn text-danger' style='display:none;'>Is your CAPSLOCK on?</span>");

jsfiddle上的现场演示