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

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


当前回答

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

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

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

其他回答

在JQuery。这涵盖了Firefox中的事件处理,并将检查意外的大写字母和小写字符。这预设了一个<input id="password" type="password" name="whatever"/>元素和一个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();
    }
});

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

这是脚本

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

还有Html

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

你可以试试。增加了一个工作示例。当焦点在输入上时,打开caps lock使led变成红色或绿色。(还没有在mac/linux上测试)

注意:两个版本都适用于我。感谢您在评论中提出建设性意见。

旧版本:https://jsbin.com/mahenes/edit?js,output

另外,这是一个修改后的版本(有人能在mac上测试并确认吗)

新版本:https://jsbin.com/xiconuv/edit?js,output

新版本:

function isCapslock(e) {
  const IS_MAC = /Mac/.test(navigator.platform);

  const charCode = e.charCode;
  const shiftKey = e.shiftKey;

  if (charCode >= 97 && charCode <= 122) {
    capsLock = shiftKey;
  } else if (charCode >= 65 && charCode <= 90
    && !(shiftKey && IS_MAC)) {
    capsLock = !shiftKey;
  }

  return capsLock;
}

旧版本:

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

对于国际字符,可以根据需要为以下键添加额外的检查。你必须获得你感兴趣的字符的键码范围,可能是通过使用一个键映射数组,它将保存你正在寻址的所有有效用例键…

大写字母A-Z或'Ä', 'Ö', 'Ü', 小写字母a-Z或0-9或'ä', 'ö', 'ü'

上面的键只是示例表示。

上面莫蒂和迭戈·维埃拉的回答是我们最终使用的,现在应该是公认的答案。然而,在我注意到它之前,我写了这个不依赖字符代码的小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;
  }
}

然后在事件处理程序中调用比如capslockisonkeydown。capslockisonkeydown(事件)

但最后我们还是用了@ motie和@Diego Vieira的回应

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