实现原理
通过 <input>
标签的 onkeypress 事件的返回false
,就可以阻止按键生效。
通过event.keyCode
拿到用户按键的keyCode,再通过String.fromCharCode()
方法转换成字符与目标字符比较
例子:假如我们在输入框中限定输入数字
<input onkeypress="return /[\d]/.test(String.fromCharCode(event.keyCode))"/>
通过 <input>
标签的 onkeypress 事件的返回false
,就可以阻止按键生效。
通过event.keyCode
拿到用户按键的keyCode,再通过String.fromCharCode()
方法转换成字符与目标字符比较
<input onkeypress="return /[\d]/.test(String.fromCharCode(event.keyCode))"/>
本文标题:input限定输入字符
本文链接:https://www.haomeiwen.com/subject/nilcyqtx.html
网友评论