0

如果可能的话,我想知道是否有人可以帮助我清理这段代码;包括将两个功能合二为一。我是 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>
4

1 回答 1

1

我会认为在重写...

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

您可以检查按下的键,如果:

  • 按下的键是大写的,并且没有按下shift,或者
  • 按下的ket是小写的,按下shift

像这样简单的东西会起作用:

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

在此处使用您的标记检查上述代码的示例。

于 2009-12-29T04:23:09.573 回答