使用 JavaScript 檢測大寫鎖定鍵(Detect Caps Lock with JavaScript)(轉)

未来的羁绊發表於2024-07-19

原文地址:Detect Caps Lock with JavaScript - 使用 JavaScript 檢測大寫鎖定

By David Walsh on February 6, 2024
作者:大衛·沃爾什,2024 年 2 月 6 日

Anyone is capable of having their caps lock key on at any given time without realizing so. Users can easily spot unwanted caps lock when typing in most inputs, but when using a password input, the problem isn't so obvious. That leads to the user's password being incorrect, which is an annoyance. Ideally developers could let the user know their caps lock key is activated.

任何人都可以在任何給定時間開啟大寫鎖定鍵,而自己卻沒有意識到。使用者在輸入大多數內容時可以輕鬆發現不需要的大寫鎖定,但在使用 password input 時,問題並不那麼明顯。這會導致使用者的密碼不正確,這很令人煩惱。理想情況下,開發人員可以讓使用者知道他們的大寫鎖定鍵已啟用。


To detect if a user has their keyboard's caps lock turn on, we'll employ KeyboardEvent's getModifierState method:

要檢測使用者是否開啟了鍵盤的大寫鎖定,我們將使用 KeyboardEventgetModifierState 方法:

document.querySelector('input[type=password]').addEventListener('keyup', function (keyboardEvent) {
    const capsLockOn = keyboardEvent.getModifierState('CapsLock');
    if (capsLockOn) {
        // Warn the user that their caps lock is on?
    }
});

I'd never seen `getModifierState` used before, so I explored the [W3C documentation](https://w3c.github.io/uievents/#event-modifier-initializers) to discover other useful values:

我以前從未見過使用 getModifierState ,因此我探索了 W3C 文件以發現其他有用的值:

dictionary EventModifierInit : UIEventInit {
  boolean ctrlKey = false;
  boolean shiftKey = false;
  boolean altKey = false;
  boolean metaKey = false;

  boolean modifierAltGraph = false;
  boolean modifierCapsLock = false;
  boolean modifierFn = false;
  boolean modifierFnLock = false;
  boolean modifierHyper = false;
  boolean modifierNumLock = false;
  boolean modifierScrollLock = false;
  boolean modifierSuper = false;
  boolean modifierSymbol = false;
  boolean modifierSymbolLock = false;
};

getModifierState provides a wealth of insight as to the user's keyboard during key-centric events. I wish I had known about getModifier earlier in my career!

getModifierState 在以按鍵為中心的事件期間提供有關使用者鍵盤的豐富見解。我希望我在職業生涯的早期就知道 getModifier

相關文章