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

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


当前回答

所以我找到了这个页面,并不是很喜欢我找到的解决方案,所以我想出了一个,并把它提供给你们所有人。对我来说,只有当我输入字母时,大写锁才重要。这段代码为我解决了问题。它快速和简单,给你一个辣椒变量引用,只要你需要它。

let capsIsOn=false; let capsChecked=false; let capsCheck=(e)=>{ let letter=e.key; if(letter.length===1 && letter.match(/[A-Za-z]/)){ if(letter!==letter.toLowerCase()){ capsIsOn=true; console.log('caps is on'); }else{ console.log('caps is off'); } capsChecked=true; window.removeEventListener("keyup",capsCheck); }else{ console.log("not a letter, not capsCheck was performed"); } } window.addEventListener("keyup",capsCheck); window.addEventListener("keyup",(e)=>{ if(capsChecked && e.keyCode===20){ capsIsOn=!capsIsOn; } });

其他回答

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

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

如何使用getModifierState()

如果指定了修饰符,getModifierState()方法返回true 按键被按下或激活。

你可以这样使用它:

function checkIfCapsLockIsOn(event) {
  var capsLockIsOn = event.getModifierState("CapsLock");
  console.log("Caps Lock activated: " + capsLockIsOn);
}

这将简单地检查CapsLock是ON还是OFF,并在控制台显示它。你可以改变函数的工作方式。

然后在keydown或keyup上使用这个函数。

<input type="text" onkeydown="checkIfCapsLockIsOn(event)">

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> 

试着使用这段代码。

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

祝你好运!