要检查 Caps Lock 是否开启,您可以使用 `getModifierState()` 方法,该方法属于 `KeyboardEvent` 对象。
const capslockIsOn = event.getModifierState(modifier);
Code language: JavaScript (javascript)
`getModifierState()` 方法在 `modifier` 处于活动状态时返回 `true`;否则返回 `false`。
`event.getModifierState('CapsLock')` 可用于检测 Caps Lock 是否开启。
假设您有一个像这样的密码字段
<input type="password" name="password" id="password" placeholder="Enter a password">
<div class="message"></div>
Code language: HTML, XML (xml)
以下示例演示了当您开启 Caps Lock 键并输入密码时,如何显示警告消息。
const password = document.querySelector('#password');
const message = document.querySelector('.message');
password.addEventListener('keyup', function (e) {
if (e.getModifierState('CapsLock')) {
message.textContent = 'Caps lock is on';
} else {
message.textContent = '';
}
});
Code language: JavaScript (javascript)
演示
本教程对您有帮助吗?