javascript 如何检测密码字段中的 CAPS LOCK 状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4810454/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I detect the CAPS LOCK state in a password field
提问by Byron Whitlock
Possible Duplicate:
How do you tell if caps lock is on using JavaScript?
In a web form, is there any way to tell if the caps lock is on ?
在网络表单中,有没有办法判断大写锁定是否打开?
I suppose I could check do a check onChangeto see if all the characters are upper case. But is there a more direct way to do this?
我想我可以检查一下onChange是否所有字符都是大写的。但是有没有更直接的方法来做到这一点?
Specifically, I am looking to implement a "YOUR CAPS LOCK IS ON" message when they enter the password field, similar to how the windows login screen does .
具体来说,我希望在他们输入密码字段时实现“YOUR CAPS LOCK IS ON”消息,类似于 Windows 登录屏幕的操作方式。
采纳答案by dmcnelis
You can find a decent example of how to do this here: http://www.codeproject.com/KB/scripting/Detect_Caps_Lock.aspx
你可以在这里找到一个很好的例子:http: //www.codeproject.com/KB/scripting/Detect_Caps_Lock.aspx
You could take that code and wrap it into a different kind of event, either, i.e. onfocus or on document load.
您可以使用该代码并将其包装到不同类型的事件中,即 onfocus 或 on document load。
You can google for an index of key codes (I'd post a link, but I don't have high enough karma to post more than one link, sorry).
你可以在谷歌上搜索关键代码的索引(我会发布一个链接,但我的业力不够高,无法发布多个链接,抱歉)。
For simplicity the codes you'd be looking for is 20 (Caps lock).
为简单起见,您要查找的代码是 20(大写锁定)。
Instructions copied here from site (license: CPOL)
此处从站点复制的说明(许可证:CPOL)
Building 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>
Now we have our script ready to go. We now need to associate this script with our form.
现在我们已经准备好了我们的脚本。我们现在需要将此脚本与我们的表单相关联。
Using the script
使用脚本
Let's add two items: a textbox and a DIV. Now we just need to call the onKeyPress event.
让我们添加两个项目:一个文本框和一个 DIV。现在我们只需要调用 onKeyPress 事件。
<input type="password" name="txtPassword" onkeypress="capLock(event)" />
<div id="divMayus" style="visibility:hidden">Caps Lock is on.</div> 

