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'); } }); |
警报将触发,但角色仍出现在文本框中。
我尝试搜索有关为什么会发生这种情况的解释,但无济于事,我们将不胜感激!
编辑
删除
谢谢
只需使用
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.
在
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, '') ); } }); |
如果现在的问题是:为什么
在您的JavaScript完成之前,浏览器将不响应您的
您不能使用
-
或者,您本来可以使用
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函数以复制您的需求。