[英]Listening for keydown / keypress events and differentiate between one and two digit numbers
I'm using an eventListener to detect numeric options in my vue app:我正在使用 eventListener 来检测我的 vue 应用程序中的数字选项:
window.addEventListener("keydown", function (e) {
switch (e.key) {
case 1:
// do stuff
break;
case 2:
// do other stuff
}
}
Since I have more than 9 options, I was wondering what the most sensible way would be to differentiate if the user is entering a one or two digit numer (eg, 1
vs 11
)?由于我有超过 9 个选项,我想知道最明智的方法是区分用户输入的是一位数还是两位数(例如
1
vs 11
)?
Ended up adapting the solution described in this blog post , by pushing all keystrokes into an array, which is cleared if there is no input after 1 sec.最终调整了这篇博文中描述的解决方案,将所有击键推入一个数组,如果 1 秒后没有输入,则该数组被清除。
let keys = [];
let timeout = null;
window.addEventListener("keydown", function (e) {
keys.push(e.key);
clearTimeout(timeout);
timeout = setTimeout(function () {
let input = parseInt(keys.join(""));
switch (input) {
case 1:
// do stuff
break;
case 11:
// do other stuff
}
keys = [];
}, 1000);
});
The switch statement is doing an implicit type conversion since e.key
is a string, and the switch case specifiers are numbers. switch 语句正在进行隐式类型转换,因为
e.key
是一个字符串,而 switch case 说明符是数字。 If you don't have more than 35 options, using base 36 digits ('1'-'9' and 'a'-'z') could be the easiest solution, in conjunction with constructing the switch statement along the lines of如果您没有超过 35 个选项,则使用基数 36 位('1'-'9' 和 'a'-'z')可能是最简单的解决方案,同时按照以下行构造 switch 语句
switch( e.key.toLowerCase() {
case '1': ... break;
.
.
.
case 'z': ... break;
}
I would hesitate before telling users they must hit a second digit within 500ms and wait that long before the first key they hit is recognized.在告诉用户他们必须在 500 毫秒内击中第二个数字并等待很长时间才能识别出他们击中的第一个键之前,我会犹豫。 :-)
:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.