Caps Lock脚本清理

时间:2009-12-29 03:28:20

标签: javascript javascript-events capslock

我想知道是否有人可以帮助我清理这些代码,如果可能的话;包括将两个函数合并为一个。我是javascript的新手,所以我真的可以使用一些帮助。

我能够让这个脚本运行得很好,我只是想知道它是否可以被改进和/或是否有任何我忽略的问题。

该脚本首先根据按键确定大写锁定是打开还是关闭。一旦确定了大写锁定状态,按下大写锁定键只需打开或关闭大写锁定警告消息。

谢谢,

杰夫

<script language="javascript">

//Caps Lock Warning
var onOff = "";
function capLock(e){
var kc = e.keyCode?e.keyCode:e.which;
var sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
var cl = document.getElementById('cl');

if(onOff == ""){

//Checks if caps lock is on.
if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))
{
cl.style.visibility = 'visible'; 
onOff = "on"; 
} 
//Checks if caps lock is off.    
else if(((kc >= 65 && kc <= 90) && sk)||((kc >= 97 && kc <= 122) && !sk))
{
cl.style.visibility = 'hidden'; 
onOff = "off"; 
}  
else
{
cl.style.visibility = 'hidden';  
}
}  
};

//Hides/shows Caps Lock warning when Caps Lock key is pressed once Caps Lock
//state is determined.
function hideMsg(e){
var cl = document.getElementById('cl');    
var KeyID = (window.event) ? event.keyCode : e.keyCode; 

if(KeyID==20 && onOff == "on")
{
cl.style.visibility = 'hidden';
onOff = "off";
}
else if(KeyID==20 && onOff == "off")
{
cl.style.visibility = 'visible';
onOff = "on";
}
}
document.onkeydown=hideMsg

</script>


<body OnLoad="document.form1.tb1.focus();">
<form name="form1">
<input name="tb1" onkeypress="capLock(event)" type="text" onLoad="javascript:this.focus" /><p />
<input name="tb2" onkeypress="capLock(event)" type="password" /><p />
<input id="Reset1" type="reset" value="reset" /><p />
<span id="cl" class="hint" style="visibility:hidden;">Caps Lock is On!
<p>Having Caps Lock on may cause you to enter your password incorrectly.</p>
<p>You should press Caps Lock to turn it off before entering your password.<p/>
</span>
</form>
</body>

1 个答案:

答案 0 :(得分:1)

我想在重写......

但首先,您如何检测CapsLock是否已开启?

您可以检查按下的按键,它将在以下情况下显示:

  • 按下的键为大写,按 按<或li>
  • 按下的小写字母是小写的,按

像这样简单的东西可行:

(function () {
  var hint = document.getElementById('cl');

  var keypressHandler = function (e) {
    e = e || window.event;
    var keyCode =  e.keyCode || e.which,
    character = String.fromCharCode(keyCode),
    isLetter = /[a-z]/i.test(character), 
    capsLockOn = isLetter && (character === character.toUpperCase() && !e.shiftKey) || 
    // Case 1: capslock on, without shift pressed
                (character === character.toLowerCase() && e.shiftKey);
    // Case 2: capslock on, with shift pressed

    hint.style.display = capsLockOn ? '' : 'none'; // show or hide the 'hint'
  }

  // Bind keypress event to both inputs:
  document.getElementById('tb1').onkeypress = 
  document.getElementById('tb2').onkeypress = keypressHandler;
})();

使用您的标记here检查上述代码的示例。