Capslock detection won't work in Javascript

不打扰是莪最后的温柔 提交于 2021-02-11 18:16:10

问题


I am trying to detect capslock in Javascript, however the code below always returns false. Firefox and IE web console says that kc and sk are undefined. Event "e" seems to contain a which element, however e.which is undefined.

Am I doing something incorrect? I am using devexpress (could this be an issue?)

Javascript

 <script>
    function isCapslock(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))
          return true;
      else
          return false; 
      }

function showCapsWarning(e) {

        if (isCapslock(e)) {
            document.getElementById("capsWarningDiv").style.visibility = 'visible';
        }
        else {
            document.getElementById("capsWarningDiv").style.visibility = 'hidden';
        }

    }
</script>

aspx file

<dx:ASPxTextBox ID="tbPassword" runat="server" ClientInstanceName="tbPassword" Password="True"                                              ToolTip="Please enter your password."
        Width="300px"  
        ClientSideEvents-KeyPress="function(s,e) {showCapsWarning(e); }"
                                                    >

This is where I got the capslock javascript code from: http://www.codeproject.com/Articles/17180/Detect-Caps-Lock-with-Javascript


回答1:


e.which was undefined within the web developer console. I noticed that the event object was using the following path in order to get to the which element: event.htmlEvent.which. Once I used e.htmlEvent it began to work correctly.




回答2:


I think a little bit late, but check this codepen: https://codepen.io/sarkiroka/full/qBbpKYY

The main idea is since 2017 every browser supports getModifierState on keyboard and mouse envents. Check this boolean to show or hide the red warning area.

let input = document.getElementById('password');
input.addEventListener('keyup', checkCapsLock);
input.addEventListener('mousedown', checkCapsLock);
let previousStateOfCapsLock=false;
function handleWarning(show){
  document.getElementById('capsLockWarning').style.display=show?'block':'none';
}
function checkCapsLock(event) {
    let isCaps = event.getModifierState('CapsLock');
  if (previousStateOfCapsLock && event.key=='CapsLock') { // now turn it off
    isCaps = false;
  }
  previousStateOfCapsLock = isCaps;
  handleWarning(isCaps);
}
.error {
  display: none;
  color: red;
  font-weight: bold;
}
<input id="password" type="password" placeholder="Enter your password"></input>
<p class="error" id="capsLockWarning">
  The Caps Lock is ON!
</p>


来源:https://stackoverflow.com/questions/19821231/capslock-detection-wont-work-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!