关于javascript:在按住Shift键的同时防止按键

Prevent keypress whilst shift key is held

我试图防止某些键被输入到输入框中,但前提是在按住shift键的同时按下该特定键:

1
2
3
4
5
6
7
$('selector').keydown(function(e) {
  console.log(e.shiftKey);
  if (e.shiftKey && e.which == 51) {
    e.preventDefault();
    alert('Disallowed');
  }
});

警报将触发,但角色仍出现在文本框中。

我尝试搜索有关为什么会发生这种情况的解释,但无济于事,我们将不胜感激!

编辑

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

谢谢


只需使用e.which而不是e.keyCode

1
2
3
4
5
6
$('#input').keydown(function(e) {
  if (e.shiftKey && e.which == 51) {
    e.preventDefault();
    alert('Disallowed');
  }
});

工作样本

因为,来自jQuery doc:

For key or mouse events, this property indicates the specific key or
button that was pressed.The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
event.which also normalizes button presses (mousedown and mouseupevents), reporting 1 for left button, 2 for middle, and 3 for right. Use event.which instead of event.button.

.keyup()上尝试

1
2
3
4
5
6
$('#input').keyup(function(e) {
   var val = $.trim( this.value );
  if (e.shiftKey && e.which == 51) {
    $(this).val(val.replace(/\\#/,''));
  }
});

演示

如果您尝试从输入中删除井号,请尝试:

1
$(this).val( val.replace(/\\u00A3/g, '') );

完整代码

1
2
3
4
5
6
$('#input').keyup(function(e) {
   var val = $.trim( this.value );
  if (e.shiftKey && e.which == 51) {
    $(this).val( val.replace(/\\u00A3/g, '') );
  }
});


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

alert是一个有趣的语句(以及confirmprompt),它暂停了JavaScript的执行,但释放了其他等待JavaScript执行的浏览器处理。它会极大地干扰调试。

在您的JavaScript完成之前,浏览器将不响应您的preventDefault()语句,将alert放入其中已暂停了您的JavaScript,因此浏览器此时尚未收到事件的返回状态,不幸的是,< x4>允许浏览器处理其他事件,即keypress,它会潜行,因此您会看到不想输入的字符。

您不能使用alert,或者,如果需要它(?!),可以将其包装在setTimeout中,这样它就不会阻塞JavaScript,并且keydown的结果将导致keypress被抑制。

-

或者,您本来可以使用keypress

1
2
3
4
5
6
7
$('selector').keypress(function(e) {
  console.log(e.shiftKey);
  if (e.which == 163) {
    e.preventDefault();
    alert('Disallowed');
  }
});

但是,这仍然不能阻止字符由替代方法输入,因此我个人不会首先对此进行娱乐。 :-/


1
2
3
4
5
6
7
8
9
10
$('#selector').keydown(function(e) {
  console.log(e.shiftKey);
  if (e.shiftKey && e.keyCode == 51) {
    $(this).prop('disabled', true);
    //do something, fade an object in...display a message, etc
    setTimeout(function(){
      $(this).prop('disabled', false);
    }, 500);
  }
});

这对我有用。

编辑

添加了setTimeout函数以复制您的需求。