在保持换档键的同时防止按键 [英] Prevent keypress whilst shift key is held

查看:97
本文介绍了在保持换档键的同时防止按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试阻止某些键输入到输入框中,但只有在 shift 键被按下时按下该特定键

I'm trying to prevent certain keys from being entered into an input box, but only if that particular key is pressed whilst the shift key is held:

$('selector').keydown(function(e) {
  console.log(e.shiftKey);
  if (e.shiftKey && e.which == 51) {
    e.preventDefault();
    alert('Disallowed');
  }
});

警告会触发但字符仍显示在文本框中。

The alert fires but the character still appears in the text box.

我一直试图寻找解释为什么会发生这种情况,但无济于事,我们将非常感谢任何帮助!

I've tried searching around for an explanation as to why this happens but to no avail, any help would be greatly appreciated!

编辑

删除提醒似乎解决了问题(这看起来很奇怪),我真的很想知道为什么它会以这种方式表现,但似乎没有任何意义。

Removing the alert seems to fix the problem (which seems bizarre), I'd really love to know why it behaves in this way though, it doesn't seem to make any sense.

谢谢

推荐答案

如果问题是:为什么 alert()有所作为?

If the question is now: why does alert() make a difference?

alert 是一个有趣的陈述(和确认 prompt ),它会暂停执行您的JavaScript,但会释放等待您执行JavaScript的任何其他浏览器处理。它会干扰调试很多。

alert is a funny statement (and confirm and prompt), it suspends execution of your JavaScript, but frees up any other browser processing that was waiting for your JavaScript to execute. It can interfere with debugging quite a lot.

浏览器不会响应你的 preventDefault()语句,直到你的JavaScript已经完成了,把 alert 放在你的JavaScript中,所以浏览器此时没有收到事件的返回状态,不幸的是 alert 允许浏览器处理其他事件,即 keypress ,它会偷偷过去,因此你会看到你不想要的角色输入显示。

The browser won't respond to your preventDefault() statement until your JavaScript has finished, putting alert in there has suspended your JavaScript, so the browser hasn't received a return status of the event at this point, and unfortunately the alert has allowed the browser to process other events, namely keypress which sneaks past and hence you see the character you don't want to be typed appear.

你不能使用 alert ,或者,如果你需要它(?!)你可以发出它包装在 setTimeout 中,这样它就不会阻止你的JavaScript,并且 keydown 的结果会导致到 keypress 被压制。

You could not use alert, or, if you need it (?!) you could issue it wrapped in a setTimeout, so that it doesn't block your JavaScript and the result of the keydown will lead to the keypress being suppressed.

-

或者,你可以在第一时间使用 keypress

Or, you could have used keypress in the first place!

$('selector').keypress(function(e) {
  console.log(e.shiftKey);
  if (e.which == 163) {
    e.preventDefault();
    alert('Disallowed');
  }
});

但仍然不能阻止其他方法输入字符,所以我不会接受这个首先,亲自。 : - /

That still doesn't prevent characters being entered by alternative methods though, so I wouldn't entertain this in the first place, personally. :-/

这篇关于在保持换档键的同时防止按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆