Есть ли прямой способ различать клавиши клавиатуры? как тип ключа? - PullRequest
0 голосов
/ 13 апреля 2020

Мне нужен способ различать клавиши символов и клавиши управления.

Type 1: A-Z?!:...
Type 2: Ctrl, Alt, Shift, Esc...

И, возможно, другая группа, такая как:

Type 3: Enter, Del, <-...

Существует ли прямой путь? как свойство или функция!

1 Ответ

1 голос
/ 13 апреля 2020

Примерно так:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example</title>
    <style>*{background: #fff;}</style>
</head>
<body>
    <h1>Key detector</h1>
    <p>Press any key, the following paragraph will tell you if you pressed a "command" key or a "char" key:</p>
    <p id="result"></p>
</body>
<script>
    const resultElement = document.querySelector('#result') // Select the result <p> to update later
    
    // Create an event listener that will be triggered each time you press a key
    document.addEventListener('keydown', e => { // This function will be triggered when you press a key
        const key = e.key // This variable will contain the key that you pressed
        const keyType = e.code.startsWith('Key') ? 'char' : 'command' // All the letters key code starts with "Key" (see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values)
        resultElement.innerHTML = `Key: ${key} | Type: ${keyType}` // Will put the result into that paragraph
    })
</script>
</html>
...