这是示例标记:
<form id="formID">
<input type="text" id="filteredInput">
<input type="text" id="anotherInput">
</form>
以下逻辑可用于捕获键盘输入(在本例中,通过 jQuery 文档就绪包装器)。
它可能读起来有点傻,但基本上,我检查我想要允许的所有内容(在你的情况下,字母 A 到 Z 不区分大小写)并且什么都不做。换句话说,默认操作是允许的,但除了 alpha 之外的任何输入都被阻止。
检查并允许标准键盘导航,例如箭头键、Home、End、Tab、Backspace、Delete 等。
注意:此代码最初是为了满足用户输入,只允许字母数字值(A - Z、a - z、0 - 9),我将这些行原样保留为注释。
<script>
jQuery( document ).ready( function() {
// keydown is used to filter input
jQuery( "#formID input" ).keydown( function( e ) {
var _key = e.which
, _keyCode = e.keyCode
, _shifted = e.shiftKey
, _altKey = e.altKey
, _controlKey = e.ctrlKey
;
//console.log( _key + ' ' + _keyCode + ' ' + _shifted + ' ' + _altKey + ' ' + _controlKey );
if( this.id === jQuery( '#filteredInput' ).prop( 'id' ) ) {
if(
// BACK, TAB
( _key === 8 || _key === 9 ) // normal keyboard nav
){}
else if(
// END, HOME, LEFT, UP, RIGHT, DOWN
( _key === 35 || _key === 36 || _key === 37 || _key === 38 || _key === 39 || _key === 40 ) // normal keyboard nav
){}
else if(
// DELETE
( _key === 46 ) // normal keyboard nav
){}
else if(
( _key >= 65 && _key <= 90 ) // a- z
//( _key >= 48 && _key <= 57 && _shifted !== true ) || // 0 - 9 (unshifted)
//( _key >= 65 && _key <= 90 ) || // a- z
//( _key >= 96 && _key <= 105 ) // number pad 0- 9
){}
else {
e.preventDefault();
}
}
});
});
</script>