gpt4 book ai didi

javascript - 有没有直接的方法来区分键盘按键?比如 key 的类型?

转载 作者:行者123 更新时间:2023-12-02 21:07:18 25 4
gpt4 key购买 nike

我需要一种方法来区分字符键和命令键。

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>

关于javascript - 有没有直接的方法来区分键盘按键?比如 key 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61193667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com