无法在keyup事件中捕获"@"(按速率符号)



我的代码中有一个keyup事件,我需要捕获@字符。我使用的是这个代码:

$(function() {
$("#textbox").keyup(function(e) {
var keynum = e.keyCode;
if (keynum && e.shiftKey && keynum == 50) {
// Made a small change.
console.log("You pressed @ and value is: " + e.target.value);
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input id="textbox" />

现在的问题是,每当用户键入shift+2的稍微快一点时,它就不起作用

编辑

您可以通过在另一个(键盘上的2(键之前几毫秒释放修饰符(shift键(来重现这个问题,即快速键入shift + 2

@ConstantingGroß能够解决这个问题,并有一个变通办法。请检查下面已接受的答案。

您可以使用KeyboardEvent.key(e.key与e.keyCode(:https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

$("#textbox").keyup(function(e) {
if (e.key === '@') {
console.log("You pressed @ and value is: " + e.target.value);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input id="textbox" />

当多键字符执行得太快时(例如,在另一个键之前几毫秒释放修饰符键(,jQuery检测多键字符似乎确实存在问题。我也能够在我的德国键盘布局上复制这一点,其中@AltGr+Q。下面是另一个跟踪@字符在输入值中出现的次数的解决方案。不是很优雅,但它确实为我提供了可靠的技巧。

$("#textbox").keyup(function(e) {
// if content is empty reset at-count
if('' === $(this).val().trim()) {
$(this).data('at-count', 0);
}
// removing all characters other than @, then counting the length
var atCount = $(this).val().replace(/[^@]/g, "").length;
// if the number of @ in the input value has increased:
if (atCount > ($(this).data('at-count') || 0)) {
console.log("You pressed @ and value is: " + e.target.value);
}
// store the current @ count for later comparison
$(this).data('at-count', atCount);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input id="textbox" />

最新更新