有没有直接的方法来区分键盘按键?像钥匙的类型?
Is there a direct way to differentiate between keyboard keys? like a key's type?
我需要一种区分字符键和命令键的方法。
Type 1: A-Z?!:...
Type 2: Ctrl, Alt, Shift, Esc...
也许另一个小组是这样的:
Type 3: Enter, Del, <-...
有直接的方式吗?像 属性 或函数!
像这样:
<!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>
我需要一种区分字符键和命令键的方法。
Type 1: A-Z?!:...
Type 2: Ctrl, Alt, Shift, Esc...
也许另一个小组是这样的:
Type 3: Enter, Del, <-...
有直接的方式吗?像 属性 或函数!
像这样:
<!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>