javascript - 计算“true”键码
当我按下键盘上的某个键时,我可以使用 e.keyCode 获取该键的 keyCode。但我得到的 keyCode 没有考虑按下的 alt/ctrl/shift 键,这会修改键代码。
幸运的是,我通过事件获取了属性 shiftKey/altKey/ctrlKey,因此我能够计算“真实”键代码。
但我不知道如何正确计算这个。我在哪里可以读到相关内容? 如果按下shift等等,是不是像减32一样简单,还是有很多例外?
When I press a key on my keyboard, I can get the keyCode of that key using e.keyCode. But the keyCode I get does not consider the pressed alt/ctrl/shift keys, wich modify the key code.
Fortunately, I get the properties shiftKey/altKey/ctrlKey with the event so I am able to calculate the "true" key code.
But I don't know how to calculate this correctly. Where can I read about that?
Is it as easy as substracting 32 if shift ist pressed and so on, or are there much exceptions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您错了,键代码不会改变,因为它们引用键盘上的特定键。无论修饰键如何,这些代码都保持不变(甚至修饰键本身也有一个键代码)。
捕获按键事件,这将允许您访问字符代码。
You're mistaken, key codes don't change because they refer to a specific key on the keyboard. Regardless of modifier keys, those codes stay the same (and even the modifier keys themselves have a key code).
Capture the keypress event, which will allow you to access character codes.
我不明白你为什么要计算“真实”的 keyCodes。如果您正在为您的网站/应用程序/其他内容创建快捷方式,您可以简单地检查按下的按钮是否是(例如)S 并且同时按下了 Ctrl。
真正的键码本身没有任何意义(除非您需要它来完成特定的任务)。
顺便说一句,您应该考虑在您的项目中使用 jQuery。它标准化了键码,因此您在任何浏览器(Windows 和操作系统)中都不会出现任何奇怪的行为。我想这更重要。
I don't understand why you would like to calculate the "true" keyCodes. If you are making shortcuts for your site/app/whatever, you could simply check if the button was pressed was (for example) S and that Ctrl was pressed at the same time.
True keyCodes have no meaning by itself (unless you need it for something specific).
Btw, you should consider using jQuery for your project. It normalizes the keyCodes so you don't have any weird behavior in any browser (Windows and OS). I guess that is more important.