如何判断大写锁定是否在使用JavaScript?

时间:2021-07-04 15:22:54

How do you tell if caps lock is on using JavaScript?

如何判断大写锁定是否在使用JavaScript?

One caveat though: I did google it and the best solution I could find was to attach an onkeypress event to every input, then check each time if the letter pressed was uppercase, and if it was, then check if shift was also held down. If it wasn't, therefore caps lock must be on. This feels really dirty and just... wasteful - surely there's a better way than this?

但有一点需要注意:我做了谷歌,我能找到的最好的解决方案是在每个输入中附加一个onkeypress事件,然后每次检查按下的字母是否为大写,如果是大写,然后检查shift是否也被按住。如果不是,则必须打开大写锁定。这感觉真的很脏,而且……浪费——肯定有比这更好的方法吗?

27 个解决方案

#1


87  

Found this interesting.... You can give it a try..

发现了这个有趣的....你可以试一试。

function isCapslock(e){

    e = (e) ? e : window.event;

    var charCode = false;
    if (e.which) {
        charCode = e.which;
    } else if (e.keyCode) {
        charCode = e.keyCode;
    }

    var shifton = false;
    if (e.shiftKey) {
        shifton = e.shiftKey;
    } else if (e.modifiers) {
        shifton = !!(e.modifiers & 4);
    }

    if (charCode >= 97 && charCode <= 122 && shifton) {
        return true;
    }

    if (charCode >= 65 && charCode <= 90 && !shifton) {
        return true;
    }

    return false;

}

For international characters, additional check can be added for the following keys as needed. You have to get the keycode range for characters you are interested in, may be by using a keymapping array which will hold all the valid use case keys you are addressing...

对于国际字符,可以根据需要为下列键添加额外的检查。您必须为您感兴趣的字符获取keycode范围,可能是通过使用keymapping数组来保存您正在寻址的所有有效用例键……

uppercase A-Z or 'Ä', 'Ö', 'Ü', lowercase a-Z or 0-9 or 'ä', 'ö', 'ü'

大写字母A - z或' A ',' O ',' U ',小写字母A - z或0 - 9 ' A ',' O ',' U '

The above keys are just sample representation.

上面的键只是示例表示。

#2


126  

In jQuery,

在jQuery中,

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

Avoid the mistake, like the backspace key, s.toLowerCase() !== s is needed.

避免错误,如backspace键,需要s.toLowerCase() != s。

#3


52  

You can use a KeyboardEvent to detect numerous keys including the caps lock on most recent browsers.

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

The getModifierState function will provide the state for:

getModifierState函数将提供以下状态:

  • Alt
  • Alt
  • AltGraph
  • AltGraph
  • CapsLock
  • 大写锁定
  • Control
  • 控制
  • Fn (Android)
  • Fn(Android)
  • Meta
  • NumLock
  • 时键盘上的数字
  • OS (Windows & Linux)
  • 操作系统(Windows和Linux)
  • ScrollLock
  • ScrollLock
  • Shift
  • 转变

This demo works in all major browsers including mobile (caniuse).

这个演示可以在所有主要的浏览器中运行,包括移动浏览器(caniuse)。

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

#4


23  

You can detect caps lock using "is letter uppercase and no shift pressed" using a keypress capture on the document. But then you better be sure that no other keypress handler pops the event bubble before it gets to the handler on the document.

您可以使用“is字母大写,不按shift键”使用文档上的按键捕获来检测大写锁定。但是,您最好确保在事件气泡到达文档上的处理程序之前,没有其他按键处理程序弹出事件泡沫。

document.onkeypress = function ( e ) {
  e = e || window.event;
  var s = String.fromCharCode( e.keyCode || e.which );
  if ( s.toUpperCase() === s && !e.shiftKey ) { // incomplete: shift + caps MAY = lowercase
    // alert('caps is on')
  }
}

You could grab the event during the capturing phase in browsers that support that, but it seems somewhat pointless to as it won't work on all browsers.

在支持捕获的浏览器中,可以在捕获阶段捕获事件,但这似乎没有什么意义,因为它不能在所有浏览器上工作。

I can't think of any other way of actually detecting caps lock status. The check is simple anyway and if non detectable characters were typed, well... then detecting wasn't necessary.

我想不出任何其他的方法来检测大写锁定状态。检查很简单,如果输入了无法检测的字符,嗯……然后检测并不是必要的。

There was an article on 24 ways on this last year. Quite good, but lacks international character support (use toUpperCase() to get around that).

去年有一篇关于24种方式的文章。很好,但是缺乏国际字符支持(使用toUpperCase()来解决这个问题)。

#5


11  

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.

许多现有的答案将检查大写锁定在转移时不是按但不会检查它如果你新闻转变和小写,或者检查,但也不会检查大写锁定,或将检查,但会考虑non-alpha键为“关闭”。这是一个改编jQuery的解决方案,将会显示一个警告如果一个α关键压帽(改变或不改变),将关闭警告如果一个α键被按下时没有限制,但不会关掉警告或数字或其他键按下时。

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

#6


11  

In JQuery. This covers the event handling in Firefox and will check for both unexpected uppercase and lowercase characters. This presupposes an <input id="password" type="password" name="whatever"/>element and a separate element with id 'capsLockWarning' that has the warning we want to show (but is hidden otherwise).

在JQuery。这将覆盖Firefox中的事件处理,并检查意外的大写和小写字符。这个前提假设一个元素和一个带有id 'capsLockWarning'的独立元素,该元素有我们想要显示的警告(但隐藏在其他情况下)。

$('#password').keypress(function(e) {
    e = e || window.event;

    // An empty field resets the visibility.
    if (this.value === '') {
        $('#capsLockWarning').hide();
        return;
    }

    // We need alphabetic characters to make a match.
    var character = String.fromCharCode(e.keyCode || e.which);
    if (character.toUpperCase() === character.toLowerCase()) {
        return;
    }

    // SHIFT doesn't usually give us a lowercase character. Check for this
    // and for when we get a lowercase character when SHIFT is enabled. 
    if ((e.shiftKey && character.toLowerCase() === character) ||
        (!e.shiftKey && character.toUpperCase() === character)) {
        $('#capsLockWarning').show();
    } else {
        $('#capsLockWarning').hide();
    }
});

#7


5  

I know this is an old topic but thought I would feed back in case it helps others. None of the answers to the question seem to work in IE8. I did however find this code that works in IE8. (Havent tested anything below IE8 yet). This can be easily modified for jQuery if required.

我知道这是一个古老的话题,但我想如果它能帮助别人,我会把它反馈回去。在IE8中,似乎没有一个问题的答案是正确的。然而,我确实找到了在IE8中工作的代码。(还没有测试IE8以下的任何东西)。如果需要,可以很容易地为jQuery修改它。

function capsCheck(e,obj){ 
    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('#'+obj.id).style.visibility = 'visible';
    } 
    else document.getElementById('#'+obj.id).style.visibility = 'hidden';
}

And the function is called through the onkeypress event like this:

这个函数是通过onkeypress事件来调用的:

<input type="password" name="txtPassword" onkeypress="capsCheck(event,this);" />
<div id="capsWarningDiv" style="visibility:hidden">Caps Lock is on.</div> 

#8


5  

The top answers here didn't work for me for a couple of reasons (un-commented code with a dead link and an incomplete solution). So I spent a few hours trying everyone's out and getting the best I could: here's mine, including jQuery and non-jQuery.

上面的答案对我不起作用有几个原因(没有注释的代码有死链接和不完整的解决方案)。所以我花了几个小时试着让大家都出来,尽我所能:这是我的,包括jQuery和非jQuery。

jQuery

Note that jQuery normalizes the event object so some checks are missing. I've also narrowed it to all password fields (since that's the biggest reason to need it) and added a warning message. This has been tested in Chrome, Mozilla, Opera, and IE6-8. Stable and catches all capslock states EXCEPT when numbers or spaces are pressed.

注意,jQuery规范化了事件对象,因此缺少一些检查。我还将它缩小到所有的密码字段(因为这是需要它的最大原因),并添加了一条警告消息。这已经在Chrome、Mozilla、Opera和IE6-8中进行了测试。稳定并捕获所有capslock状态,除非按下数字或空格。

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

    var $warn = $(this).next(".capsWarn"); // handle the warning mssg
    var kc = e.which; //get keycode
    var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
    var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
    // 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) ) {
        $warn.show();
    } else {
        $warn.hide();
    }

}).after("<span class='capsWarn error' style='display:none;'>Is your CAPSLOCK on?</span>");

Without jQuery

Some of the other jQuery-less solutions lacked IE fallbacks. @Zappa patched it.

其他一些没有jquery的解决方案缺少IE回退。@Zappa修补它。

document.onkeypress = function ( e ) {
    e = (e) ? e : window.event;

    var kc = ( e.keyCode ) ? e.keyCode : e.which; // get keycode
    var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
    var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
    var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed -- works for IE8-

    // uppercase w/out shift or lowercase with shift == caps lock
    if ( (isUp && !isShift) || (isLow && isShift) ) {
        alert("CAPSLOCK is on."); // do your thing here
    } else {
        // no CAPSLOCK to speak of
    }

}

Note: Check out the solutions of @Borgar, @Joe Liversedge, and @Zappa, and the plugin developed by @Pavel Azanov, which I have not tried but is a good idea. If someone knows a way to expand the scope beyond A-Za-z, please edit away. Also, jQuery versions of this question are closed as duplicate, so that's why I'm posting both here.

注意:查看@Borgar、@Joe Liversedge和@Zappa的解决方案,以及@Pavel Azanov开发的插件,我还没有尝试过,但这是个好主意。如果有人知道扩展a- za -z范围的方法,请编辑。同样,这个问题的jQuery版本也是复制的,所以我在这里同时发布这两个版本。

#9


5  

This is a solution that, in addition to checking state when writing, also toggles the warning message each time the Caps Lock key is pressed (with some limitations).

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

It also supports non-english letters outside the A-Z range, as it checks the string character against toUpperCase() and toLowerCase() instead of checking against character range.

它还支持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>

Note that observing caps lock toggling is only useful if we know the state of the caps lock before the Caps Lock key is pressed. The current caps lock state is kept with a caps JavaScript property on the password element. This is set the first time we have a validation of the caps lock state when the user presses a letter that can be upper or lower case. If the window loses focus, we can no longer observe caps lock toggling, so we need to reset to an unknown state.

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

#10


3  

Recently there was a similar question on hashcode.com, and I created a jQuery plugin to deal with it. It also supports the recognition of caps lock on numbers. (On the standard German keyboard layout caps lock has effect on numbers).

最近在hashcode.com上有一个类似的问题,我创建了一个jQuery插件来处理它。它还支持对数字的大写锁定的识别。(在标准的德国键盘布局中,大写锁定对数字有影响)。

You can check the latest version here: jquery.capsChecker

您可以在这里查看最新版本:jquery.capsChecker。

#11


3  

For jQuery with twitter bootstrap

对于jQuery和twitter引导。

Check caps locked for the following characters:

检查下列字符是否锁住大写:

uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';', '*', '''

大写字母A- z或A、O、U !”、“””、“§”、“美元”、“%”、“&”、“/”、“(”、“)”、“=”、“:”、“,”、“*”、“

lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ',', '+', '#'

小写的a- z或0-9或“a”、“o”、“u”。”、“,”、“+”、“#”

/* 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>");

live demo on jsfiddle

现场演示在jsfiddle

#12


2  

This code detects caps lock no matter the case or if the shift key is pressed:

此代码检测大写锁定,无论情况或是否按shift键:

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

#13


2  

I wrote a library called capsLock which does exactly what you want it to do.

我写了一个叫capsLock的库,它可以做你想做的事情。

Just include it on your web pages:

只要把它包括在你的网页:

<script src="https://rawgit.com/aaditmshah/capsLock/master/capsLock.js"></script>

Then use it as follows:

然后使用如下:

alert(capsLock.status);

capsLock.observe(function (status) {
    alert(status);
});

See the demo: http://jsfiddle.net/3EXMd/

看到演示:http://jsfiddle.net/3EXMd/

The status is updated when you press the Caps Lock key. It only uses the Shift key hack to determine the correct status of the Caps Lock key. Initially the status is false. So beware.

当您按下大写锁定键时,状态将被更新。它只使用Shift键破解来确定大写锁定键的正确状态。最初的状态是错误的。所以要小心。

#14


2  

Yet another version, clear and simple, handles shifted capsLock, and not constrained to ascii I think:

另一个版本,清晰而简单,处理移位的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];

Edit: Sense of capsLockOn was reversed, doh, fixed.

编辑:capsLockOn的感觉颠倒了,doh,固定了。

Edit #2: After checking this out some more, I've made a few changes, a bit more detailed code unfortunately, but it handles more actions appropriately.

编辑#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.

    使用e。charCode代替e。keyCode和检查0值会跳过很多非字符按键,而不会对特定语言或字符集进行编码。从我的理解来看,它的兼容性稍差一些,所以更老的、非主流的、或者移动的浏览器可能不像这段代码所期望的那样,但无论如何,这是值得的。

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

    检查已知的标点符号列表可以防止它们被视为假否定,因为它们不受大写锁定的影响。如果没有这个,当您键入任何这些标点字符时,大写锁定指示器将被隐藏。通过指定一个被排除的集合,而不是包含的集合,它应该与扩展字符更加兼容。这是最丑陋、最特别的部分,非西方语言有可能有足够不同的标点和/或标点符号,成为一个问题,但在我看来,这是值得的,至少对我来说是这样。

#15


2  

A variable that shows caps lock state:

显示大写锁定状态的变量:

let isCapsLockOn = false;

document.addEventListener( 'keydown', function( event ) {
  var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
  if(isCapsLockOn !== caps) isCapsLockOn = caps;
});

document.addEventListener( 'keyup', function( event ) {
  var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
  if(isCapsLockOn !== caps) isCapsLockOn = caps;
});

works on all browsers => canIUse

适用于所有浏览器=> canIUse

#16


1  

Based on answer of @joshuahedlund since it worked fine for me.

基于@joshuahedlund的回答,因为它对我很有效。

I made the code a function so it can be reused, and linked it to the body in my case. It can be linked to the password field only if you prefer.

我使代码成为一个函数,以便可以重用它,并在我的例子中将它链接到body。只有您愿意,才能将它链接到密码字段。

<html>
<head>
<script language="javascript" type="text/javascript" >
function checkCapsLock(e, divId) { 
    if(e){
        e = e;
    } else {
        e = window.event;
    }
    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)) {
        $(divId).style.display='block';
    } else if ((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey)||
      (s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) { //caps is off
        $(divId).style.display='none';
   } //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)
 }
</script>
<style>    
.errorDiv {
    display: none;
    font-size: 12px;
    color: red;
    word-wrap: break-word;
    text-overflow: clip;
    max-width: 200px;
    font-weight: normal;
}
</style>
</head>
<body  onkeypress="checkCapsLock(event, 'CapsWarn');" >
...
<input name="password" id="password" type="password" autocomplete="off">
<div id="CapsWarn" class="errorDiv">Capslock is ON !</div>
...
</body>
</html>

#17


1  

Mottie's and Diego Vieira's response above is what we ended up using and should be the accepted answer now. However, before I noticed it, I wrote this little javascript function that doesn't rely on character codes...

莫特蒂和迪亚哥维埃拉的回答是我们最后使用的,现在应该是大家接受的答案。然而,在我注意到它之前,我编写了这个不依赖字符代码的javascript函数……

var capsLockIsOnKeyDown = {shiftWasDownDuringLastChar: false,
  capsLockIsOnKeyDown: function(event) {
    var eventWasShiftKeyDown = event.which === 16;
    var capsLockIsOn = false;
    var shifton = false;
    if (event.shiftKey) {
        shifton = event.shiftKey;
    } else if (event.modifiers) {
        shifton = !!(event.modifiers & 4);
    }

    if (event.target.value.length > 0 && !eventWasShiftKeyDown) {
      var lastChar = event.target.value[event.target.value.length-1];
      var isAlpha = /^[a-zA-Z]/.test(lastChar);

      if (isAlpha) {
        if (lastChar.toUpperCase() === lastChar && lastChar.toLowerCase() !== lastChar
          && !event.shiftKey && !capsLockIsOnKeyDown.shiftWasDownDuringLastChar) {
          capsLockIsOn =  true;
        }
      }
    }
    capsLockIsOnKeyDown.shiftWasDownDuringLastChar = shifton;
    return capsLockIsOn;
  }
}

Then call it in an event handler like so capsLockIsOnKeyDown.capsLockIsOnKeyDown(event)

然后在事件处理程序中调用它,如capsLockIsOnKeyDown.capsLockIsOnKeyDown(事件)

But again, we ended up just using @Mottie s and @Diego Vieira s response

但是,我们还是使用了@Mottie s和@Diego Vieira的回复

#18


0  

In this below code it will be show alert when Caps lock on and they press key using shift.

在下面的代码中,当大写锁定并使用shift键时,将显示警告。

if we return false; then current char will not append to text page.

如果我们返回false;然后,当前char将不会追加到文本页面。

$('#password').keypress(function(e) { 
    // e.keyCode is not work in FF, SO, it will
    // automatically get the value of e.which.  
    var s = String.fromCharCode( e.keyCode || e.which );
    if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
            alert('caps is on');
            return false;
    }
else  if ( s.toUpperCase() !== s) {
            alert('caps is on and Shiftkey pressed');
            return false;
    }
});

#19


0  

try this out simple code in easy to understand

试试这个简单的代码,容易理解。

This is the Script

这是脚本

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

And the Html

和Html

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

#20


0  

try to use this code.

尝试使用此代码。

$('selectorOnTheInputTextBox').keypress(function (e) {
        var charCode = e.target.value.charCodeAt(e.target.value.length - 1)
        var capsOn = 
            e.keyCode && 
            !e.shiftKey &&
            !e.ctrlKey &&
            charCode >= 65 && 
            charCode <= 90;

            if (capsOn) 
               //action if true
            else
               //action if false
});

Good Luck :)

祝你好运:)

#21


0  

You could use this script. It should work well on Windows even if the Shift key is pressed but it won't work on Mac OS if so.

您可以使用这个脚本。即使按下Shift键,它也能在Windows上正常工作,但如果按下Shift键,它在Mac OS上就不行了。

#22


0  

Here is a custom jquery plugin, using jquery ui, made up of all the good ideas on this page and leverages the tooltip widget. The caps lock message is auto applied all password boxes and requires no changes to your current html.

这是一个自定义jquery插件,使用jquery ui,由这个页面上的所有好想法组成,并利用工具提示小部件。大写锁定消息是自动应用所有的密码框,并且不需要对当前的html修改。

Custom plug in code...

自定义插入代码…

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

Apply to all password elements...

应用于所有密码元素…

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

#23


0  

Javascript Code

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>

We now need to associate this script using Html

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

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

#24


0  

React

反应

onKeyPress(event) { 
        let self = this;
        self.setState({
            capsLock: isCapsLockOn(self, event)
        });
    }

    onKeyUp(event) { 
        let self = this;
        let key = event.key;
        if( key === 'Shift') {
            self.shift = false;
        }
    }

    <div>
     <input name={this.props.name} onKeyDown={(e)=>this.onKeyPress(e)} onKeyUp={(e)=>this.onKeyUp(e)} onChange={this.props.onChange}/>
                {this.capsLockAlert()}
</div>

function isCapsLockOn(component, event) {
        let key = event.key;
        let keyCode = event.keyCode;

        component.lastKeyPressed = key;

        if( key === 'Shift') {
            component.shift = true;
        } 

        if (key === 'CapsLock') {
            let newCapsLockState = !component.state.capsLock;
            component.caps = newCapsLockState;
            return newCapsLockState;
        } else {
            if ((component.lastKeyPressed !== 'Shift' && (key === key.toUpperCase() && (keyCode >= 65 && keyCode <= 90)) && !component.shift) || component.caps ) {
                component.caps = true;
                return true;
            } else {
                component.caps = false;
                return false;
            }
        }
    }

#25


-1  

When you type, if caplock is on, it could automatically convert the current char to lowercase. That way even if caplocks is on, it will not behave like it is on the current page. To inform your users you could display a text saying that caplocks is on, but that the form entries are converted.

当您输入时,如果caplock是on的,它可以自动将当前字符转换为小写。这样,即使caplocks设置为on,它也不会像在当前页面上一样运行。要通知您的用户,您可以显示一个文本,说明caplocks是on的,但是表单条目是被转换的。

#26


-1  

There is a much simpler solution for detecting caps-lock:

有一种更简单的方法可以检测caps-lock:

function isCapsLockOn(event) {
    var s = String.fromCharCode(event.which);
    if (s.toUpperCase() === s && s.toLowerCase() !== s && !event.shiftKey) {
        return true;
    }
}

#27


-7  

In jQuery:

jQuery:

$('some_element').keypress(function(e){
       if(e.keyCode == 20){
             //caps lock was pressed
       }
});

This jQuery plugin (code) implements the same idea as in Rajesh's answer a bit more succinctly.

这个jQuery插件(代码)实现了与Rajesh的答案相同的想法,并且更加简洁。

#1


87  

Found this interesting.... You can give it a try..

发现了这个有趣的....你可以试一试。

function isCapslock(e){

    e = (e) ? e : window.event;

    var charCode = false;
    if (e.which) {
        charCode = e.which;
    } else if (e.keyCode) {
        charCode = e.keyCode;
    }

    var shifton = false;
    if (e.shiftKey) {
        shifton = e.shiftKey;
    } else if (e.modifiers) {
        shifton = !!(e.modifiers & 4);
    }

    if (charCode >= 97 && charCode <= 122 && shifton) {
        return true;
    }

    if (charCode >= 65 && charCode <= 90 && !shifton) {
        return true;
    }

    return false;

}

For international characters, additional check can be added for the following keys as needed. You have to get the keycode range for characters you are interested in, may be by using a keymapping array which will hold all the valid use case keys you are addressing...

对于国际字符,可以根据需要为下列键添加额外的检查。您必须为您感兴趣的字符获取keycode范围,可能是通过使用keymapping数组来保存您正在寻址的所有有效用例键……

uppercase A-Z or 'Ä', 'Ö', 'Ü', lowercase a-Z or 0-9 or 'ä', 'ö', 'ü'

大写字母A - z或' A ',' O ',' U ',小写字母A - z或0 - 9 ' A ',' O ',' U '

The above keys are just sample representation.

上面的键只是示例表示。

#2


126  

In jQuery,

在jQuery中,

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

Avoid the mistake, like the backspace key, s.toLowerCase() !== s is needed.

避免错误,如backspace键,需要s.toLowerCase() != s。

#3


52  

You can use a KeyboardEvent to detect numerous keys including the caps lock on most recent browsers.

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

The getModifierState function will provide the state for:

getModifierState函数将提供以下状态:

  • Alt
  • Alt
  • AltGraph
  • AltGraph
  • CapsLock
  • 大写锁定
  • Control
  • 控制
  • Fn (Android)
  • Fn(Android)
  • Meta
  • NumLock
  • 时键盘上的数字
  • OS (Windows & Linux)
  • 操作系统(Windows和Linux)
  • ScrollLock
  • ScrollLock
  • Shift
  • 转变

This demo works in all major browsers including mobile (caniuse).

这个演示可以在所有主要的浏览器中运行,包括移动浏览器(caniuse)。

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

#4


23  

You can detect caps lock using "is letter uppercase and no shift pressed" using a keypress capture on the document. But then you better be sure that no other keypress handler pops the event bubble before it gets to the handler on the document.

您可以使用“is字母大写,不按shift键”使用文档上的按键捕获来检测大写锁定。但是,您最好确保在事件气泡到达文档上的处理程序之前,没有其他按键处理程序弹出事件泡沫。

document.onkeypress = function ( e ) {
  e = e || window.event;
  var s = String.fromCharCode( e.keyCode || e.which );
  if ( s.toUpperCase() === s && !e.shiftKey ) { // incomplete: shift + caps MAY = lowercase
    // alert('caps is on')
  }
}

You could grab the event during the capturing phase in browsers that support that, but it seems somewhat pointless to as it won't work on all browsers.

在支持捕获的浏览器中,可以在捕获阶段捕获事件,但这似乎没有什么意义,因为它不能在所有浏览器上工作。

I can't think of any other way of actually detecting caps lock status. The check is simple anyway and if non detectable characters were typed, well... then detecting wasn't necessary.

我想不出任何其他的方法来检测大写锁定状态。检查很简单,如果输入了无法检测的字符,嗯……然后检测并不是必要的。

There was an article on 24 ways on this last year. Quite good, but lacks international character support (use toUpperCase() to get around that).

去年有一篇关于24种方式的文章。很好,但是缺乏国际字符支持(使用toUpperCase()来解决这个问题)。

#5


11  

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.

许多现有的答案将检查大写锁定在转移时不是按但不会检查它如果你新闻转变和小写,或者检查,但也不会检查大写锁定,或将检查,但会考虑non-alpha键为“关闭”。这是一个改编jQuery的解决方案,将会显示一个警告如果一个α关键压帽(改变或不改变),将关闭警告如果一个α键被按下时没有限制,但不会关掉警告或数字或其他键按下时。

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

#6


11  

In JQuery. This covers the event handling in Firefox and will check for both unexpected uppercase and lowercase characters. This presupposes an <input id="password" type="password" name="whatever"/>element and a separate element with id 'capsLockWarning' that has the warning we want to show (but is hidden otherwise).

在JQuery。这将覆盖Firefox中的事件处理,并检查意外的大写和小写字符。这个前提假设一个元素和一个带有id 'capsLockWarning'的独立元素,该元素有我们想要显示的警告(但隐藏在其他情况下)。

$('#password').keypress(function(e) {
    e = e || window.event;

    // An empty field resets the visibility.
    if (this.value === '') {
        $('#capsLockWarning').hide();
        return;
    }

    // We need alphabetic characters to make a match.
    var character = String.fromCharCode(e.keyCode || e.which);
    if (character.toUpperCase() === character.toLowerCase()) {
        return;
    }

    // SHIFT doesn't usually give us a lowercase character. Check for this
    // and for when we get a lowercase character when SHIFT is enabled. 
    if ((e.shiftKey && character.toLowerCase() === character) ||
        (!e.shiftKey && character.toUpperCase() === character)) {
        $('#capsLockWarning').show();
    } else {
        $('#capsLockWarning').hide();
    }
});

#7


5  

I know this is an old topic but thought I would feed back in case it helps others. None of the answers to the question seem to work in IE8. I did however find this code that works in IE8. (Havent tested anything below IE8 yet). This can be easily modified for jQuery if required.

我知道这是一个古老的话题,但我想如果它能帮助别人,我会把它反馈回去。在IE8中,似乎没有一个问题的答案是正确的。然而,我确实找到了在IE8中工作的代码。(还没有测试IE8以下的任何东西)。如果需要,可以很容易地为jQuery修改它。

function capsCheck(e,obj){ 
    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('#'+obj.id).style.visibility = 'visible';
    } 
    else document.getElementById('#'+obj.id).style.visibility = 'hidden';
}

And the function is called through the onkeypress event like this:

这个函数是通过onkeypress事件来调用的:

<input type="password" name="txtPassword" onkeypress="capsCheck(event,this);" />
<div id="capsWarningDiv" style="visibility:hidden">Caps Lock is on.</div> 

#8


5  

The top answers here didn't work for me for a couple of reasons (un-commented code with a dead link and an incomplete solution). So I spent a few hours trying everyone's out and getting the best I could: here's mine, including jQuery and non-jQuery.

上面的答案对我不起作用有几个原因(没有注释的代码有死链接和不完整的解决方案)。所以我花了几个小时试着让大家都出来,尽我所能:这是我的,包括jQuery和非jQuery。

jQuery

Note that jQuery normalizes the event object so some checks are missing. I've also narrowed it to all password fields (since that's the biggest reason to need it) and added a warning message. This has been tested in Chrome, Mozilla, Opera, and IE6-8. Stable and catches all capslock states EXCEPT when numbers or spaces are pressed.

注意,jQuery规范化了事件对象,因此缺少一些检查。我还将它缩小到所有的密码字段(因为这是需要它的最大原因),并添加了一条警告消息。这已经在Chrome、Mozilla、Opera和IE6-8中进行了测试。稳定并捕获所有capslock状态,除非按下数字或空格。

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

    var $warn = $(this).next(".capsWarn"); // handle the warning mssg
    var kc = e.which; //get keycode
    var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
    var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
    // 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) ) {
        $warn.show();
    } else {
        $warn.hide();
    }

}).after("<span class='capsWarn error' style='display:none;'>Is your CAPSLOCK on?</span>");

Without jQuery

Some of the other jQuery-less solutions lacked IE fallbacks. @Zappa patched it.

其他一些没有jquery的解决方案缺少IE回退。@Zappa修补它。

document.onkeypress = function ( e ) {
    e = (e) ? e : window.event;

    var kc = ( e.keyCode ) ? e.keyCode : e.which; // get keycode
    var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
    var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
    var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed -- works for IE8-

    // uppercase w/out shift or lowercase with shift == caps lock
    if ( (isUp && !isShift) || (isLow && isShift) ) {
        alert("CAPSLOCK is on."); // do your thing here
    } else {
        // no CAPSLOCK to speak of
    }

}

Note: Check out the solutions of @Borgar, @Joe Liversedge, and @Zappa, and the plugin developed by @Pavel Azanov, which I have not tried but is a good idea. If someone knows a way to expand the scope beyond A-Za-z, please edit away. Also, jQuery versions of this question are closed as duplicate, so that's why I'm posting both here.

注意:查看@Borgar、@Joe Liversedge和@Zappa的解决方案,以及@Pavel Azanov开发的插件,我还没有尝试过,但这是个好主意。如果有人知道扩展a- za -z范围的方法,请编辑。同样,这个问题的jQuery版本也是复制的,所以我在这里同时发布这两个版本。

#9


5  

This is a solution that, in addition to checking state when writing, also toggles the warning message each time the Caps Lock key is pressed (with some limitations).

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

It also supports non-english letters outside the A-Z range, as it checks the string character against toUpperCase() and toLowerCase() instead of checking against character range.

它还支持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>

Note that observing caps lock toggling is only useful if we know the state of the caps lock before the Caps Lock key is pressed. The current caps lock state is kept with a caps JavaScript property on the password element. This is set the first time we have a validation of the caps lock state when the user presses a letter that can be upper or lower case. If the window loses focus, we can no longer observe caps lock toggling, so we need to reset to an unknown state.

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

#10


3  

Recently there was a similar question on hashcode.com, and I created a jQuery plugin to deal with it. It also supports the recognition of caps lock on numbers. (On the standard German keyboard layout caps lock has effect on numbers).

最近在hashcode.com上有一个类似的问题,我创建了一个jQuery插件来处理它。它还支持对数字的大写锁定的识别。(在标准的德国键盘布局中,大写锁定对数字有影响)。

You can check the latest version here: jquery.capsChecker

您可以在这里查看最新版本:jquery.capsChecker。

#11


3  

For jQuery with twitter bootstrap

对于jQuery和twitter引导。

Check caps locked for the following characters:

检查下列字符是否锁住大写:

uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';', '*', '''

大写字母A- z或A、O、U !”、“””、“§”、“美元”、“%”、“&”、“/”、“(”、“)”、“=”、“:”、“,”、“*”、“

lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ',', '+', '#'

小写的a- z或0-9或“a”、“o”、“u”。”、“,”、“+”、“#”

/* 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>");

live demo on jsfiddle

现场演示在jsfiddle

#12


2  

This code detects caps lock no matter the case or if the shift key is pressed:

此代码检测大写锁定,无论情况或是否按shift键:

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

#13


2  

I wrote a library called capsLock which does exactly what you want it to do.

我写了一个叫capsLock的库,它可以做你想做的事情。

Just include it on your web pages:

只要把它包括在你的网页:

<script src="https://rawgit.com/aaditmshah/capsLock/master/capsLock.js"></script>

Then use it as follows:

然后使用如下:

alert(capsLock.status);

capsLock.observe(function (status) {
    alert(status);
});

See the demo: http://jsfiddle.net/3EXMd/

看到演示:http://jsfiddle.net/3EXMd/

The status is updated when you press the Caps Lock key. It only uses the Shift key hack to determine the correct status of the Caps Lock key. Initially the status is false. So beware.

当您按下大写锁定键时,状态将被更新。它只使用Shift键破解来确定大写锁定键的正确状态。最初的状态是错误的。所以要小心。

#14


2  

Yet another version, clear and simple, handles shifted capsLock, and not constrained to ascii I think:

另一个版本,清晰而简单,处理移位的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];

Edit: Sense of capsLockOn was reversed, doh, fixed.

编辑:capsLockOn的感觉颠倒了,doh,固定了。

Edit #2: After checking this out some more, I've made a few changes, a bit more detailed code unfortunately, but it handles more actions appropriately.

编辑#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.

    使用e。charCode代替e。keyCode和检查0值会跳过很多非字符按键,而不会对特定语言或字符集进行编码。从我的理解来看,它的兼容性稍差一些,所以更老的、非主流的、或者移动的浏览器可能不像这段代码所期望的那样,但无论如何,这是值得的。

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

    检查已知的标点符号列表可以防止它们被视为假否定,因为它们不受大写锁定的影响。如果没有这个,当您键入任何这些标点字符时,大写锁定指示器将被隐藏。通过指定一个被排除的集合,而不是包含的集合,它应该与扩展字符更加兼容。这是最丑陋、最特别的部分,非西方语言有可能有足够不同的标点和/或标点符号,成为一个问题,但在我看来,这是值得的,至少对我来说是这样。

#15


2  

A variable that shows caps lock state:

显示大写锁定状态的变量:

let isCapsLockOn = false;

document.addEventListener( 'keydown', function( event ) {
  var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
  if(isCapsLockOn !== caps) isCapsLockOn = caps;
});

document.addEventListener( 'keyup', function( event ) {
  var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
  if(isCapsLockOn !== caps) isCapsLockOn = caps;
});

works on all browsers => canIUse

适用于所有浏览器=> canIUse

#16


1  

Based on answer of @joshuahedlund since it worked fine for me.

基于@joshuahedlund的回答,因为它对我很有效。

I made the code a function so it can be reused, and linked it to the body in my case. It can be linked to the password field only if you prefer.

我使代码成为一个函数,以便可以重用它,并在我的例子中将它链接到body。只有您愿意,才能将它链接到密码字段。

<html>
<head>
<script language="javascript" type="text/javascript" >
function checkCapsLock(e, divId) { 
    if(e){
        e = e;
    } else {
        e = window.event;
    }
    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)) {
        $(divId).style.display='block';
    } else if ((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey)||
      (s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) { //caps is off
        $(divId).style.display='none';
   } //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)
 }
</script>
<style>    
.errorDiv {
    display: none;
    font-size: 12px;
    color: red;
    word-wrap: break-word;
    text-overflow: clip;
    max-width: 200px;
    font-weight: normal;
}
</style>
</head>
<body  onkeypress="checkCapsLock(event, 'CapsWarn');" >
...
<input name="password" id="password" type="password" autocomplete="off">
<div id="CapsWarn" class="errorDiv">Capslock is ON !</div>
...
</body>
</html>

#17


1  

Mottie's and Diego Vieira's response above is what we ended up using and should be the accepted answer now. However, before I noticed it, I wrote this little javascript function that doesn't rely on character codes...

莫特蒂和迪亚哥维埃拉的回答是我们最后使用的,现在应该是大家接受的答案。然而,在我注意到它之前,我编写了这个不依赖字符代码的javascript函数……

var capsLockIsOnKeyDown = {shiftWasDownDuringLastChar: false,
  capsLockIsOnKeyDown: function(event) {
    var eventWasShiftKeyDown = event.which === 16;
    var capsLockIsOn = false;
    var shifton = false;
    if (event.shiftKey) {
        shifton = event.shiftKey;
    } else if (event.modifiers) {
        shifton = !!(event.modifiers & 4);
    }

    if (event.target.value.length > 0 && !eventWasShiftKeyDown) {
      var lastChar = event.target.value[event.target.value.length-1];
      var isAlpha = /^[a-zA-Z]/.test(lastChar);

      if (isAlpha) {
        if (lastChar.toUpperCase() === lastChar && lastChar.toLowerCase() !== lastChar
          && !event.shiftKey && !capsLockIsOnKeyDown.shiftWasDownDuringLastChar) {
          capsLockIsOn =  true;
        }
      }
    }
    capsLockIsOnKeyDown.shiftWasDownDuringLastChar = shifton;
    return capsLockIsOn;
  }
}

Then call it in an event handler like so capsLockIsOnKeyDown.capsLockIsOnKeyDown(event)

然后在事件处理程序中调用它,如capsLockIsOnKeyDown.capsLockIsOnKeyDown(事件)

But again, we ended up just using @Mottie s and @Diego Vieira s response

但是,我们还是使用了@Mottie s和@Diego Vieira的回复

#18


0  

In this below code it will be show alert when Caps lock on and they press key using shift.

在下面的代码中,当大写锁定并使用shift键时,将显示警告。

if we return false; then current char will not append to text page.

如果我们返回false;然后,当前char将不会追加到文本页面。

$('#password').keypress(function(e) { 
    // e.keyCode is not work in FF, SO, it will
    // automatically get the value of e.which.  
    var s = String.fromCharCode( e.keyCode || e.which );
    if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
            alert('caps is on');
            return false;
    }
else  if ( s.toUpperCase() !== s) {
            alert('caps is on and Shiftkey pressed');
            return false;
    }
});

#19


0  

try this out simple code in easy to understand

试试这个简单的代码,容易理解。

This is the Script

这是脚本

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

And the Html

和Html

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

#20


0  

try to use this code.

尝试使用此代码。

$('selectorOnTheInputTextBox').keypress(function (e) {
        var charCode = e.target.value.charCodeAt(e.target.value.length - 1)
        var capsOn = 
            e.keyCode && 
            !e.shiftKey &&
            !e.ctrlKey &&
            charCode >= 65 && 
            charCode <= 90;

            if (capsOn) 
               //action if true
            else
               //action if false
});

Good Luck :)

祝你好运:)

#21


0  

You could use this script. It should work well on Windows even if the Shift key is pressed but it won't work on Mac OS if so.

您可以使用这个脚本。即使按下Shift键,它也能在Windows上正常工作,但如果按下Shift键,它在Mac OS上就不行了。

#22


0  

Here is a custom jquery plugin, using jquery ui, made up of all the good ideas on this page and leverages the tooltip widget. The caps lock message is auto applied all password boxes and requires no changes to your current html.

这是一个自定义jquery插件,使用jquery ui,由这个页面上的所有好想法组成,并利用工具提示小部件。大写锁定消息是自动应用所有的密码框,并且不需要对当前的html修改。

Custom plug in code...

自定义插入代码…

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

Apply to all password elements...

应用于所有密码元素…

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

#23


0  

Javascript Code

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>

We now need to associate this script using Html

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

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

#24


0  

React

反应

onKeyPress(event) { 
        let self = this;
        self.setState({
            capsLock: isCapsLockOn(self, event)
        });
    }

    onKeyUp(event) { 
        let self = this;
        let key = event.key;
        if( key === 'Shift') {
            self.shift = false;
        }
    }

    <div>
     <input name={this.props.name} onKeyDown={(e)=>this.onKeyPress(e)} onKeyUp={(e)=>this.onKeyUp(e)} onChange={this.props.onChange}/>
                {this.capsLockAlert()}
</div>

function isCapsLockOn(component, event) {
        let key = event.key;
        let keyCode = event.keyCode;

        component.lastKeyPressed = key;

        if( key === 'Shift') {
            component.shift = true;
        } 

        if (key === 'CapsLock') {
            let newCapsLockState = !component.state.capsLock;
            component.caps = newCapsLockState;
            return newCapsLockState;
        } else {
            if ((component.lastKeyPressed !== 'Shift' && (key === key.toUpperCase() && (keyCode >= 65 && keyCode <= 90)) && !component.shift) || component.caps ) {
                component.caps = true;
                return true;
            } else {
                component.caps = false;
                return false;
            }
        }
    }

#25


-1  

When you type, if caplock is on, it could automatically convert the current char to lowercase. That way even if caplocks is on, it will not behave like it is on the current page. To inform your users you could display a text saying that caplocks is on, but that the form entries are converted.

当您输入时,如果caplock是on的,它可以自动将当前字符转换为小写。这样,即使caplocks设置为on,它也不会像在当前页面上一样运行。要通知您的用户,您可以显示一个文本,说明caplocks是on的,但是表单条目是被转换的。

#26


-1  

There is a much simpler solution for detecting caps-lock:

有一种更简单的方法可以检测caps-lock:

function isCapsLockOn(event) {
    var s = String.fromCharCode(event.which);
    if (s.toUpperCase() === s && s.toLowerCase() !== s && !event.shiftKey) {
        return true;
    }
}

#27


-7  

In jQuery:

jQuery:

$('some_element').keypress(function(e){
       if(e.keyCode == 20){
             //caps lock was pressed
       }
});

This jQuery plugin (code) implements the same idea as in Rajesh's answer a bit more succinctly.

这个jQuery插件(代码)实现了与Rajesh的答案相同的想法,并且更加简洁。