使用jQuery是否可以禁用特定的键盘按键(例如星号或字符串)?
你不能直接禁用按键,但你可以使用jQuery捕获它并覆盖其操作(返回false)。下面的示例捕获回车键。只需将13更改为你需要禁用的任何按键代码。
$("input").keypress(function (evt) {
var keycode = evt.charCode || evt.keyCode;
if (keycode == 13) { //Enter key's keycode
return false;
}
});
我不得不禁用除了F11和ESC之外的所有键。所以我这样做。希望这可以帮助到某些人。:)
$(document).on('keydown',function(e)
{
var key = e.charCode || e.keyCode;
if(key == 122 || key == 27 )
{}
else
e.preventDefault();
});
处理 onKeyDown
,然后在其上调用 preventDefault
。
// Bind this keypress function to the html (not sure about this) or body tags of your page
$("body").keypress(function (evt) {
//Determine where the character code is coming from
var charCode = evt.charCode || evt.keyCode;
if (charCode == 13) { //Enter key's keycode, could be any other key
return false;
}
});
通过返回 false,你告诉浏览器不允许按键事件。
OnKeyUp,Down-EventListener
添加到您的 HTML 页面中,如果按下的键是您想要忽略的键,只需调用 preventDefault
函数即可。您可以像这样使用以下插件:
$('#text_input').filter_input({regex:'[a-z]'})
;
http://www.thimbleopensource.com/tutorials-snippets/jquery-plugin-filter-text-input