美文网首页
input限定输入字符

input限定输入字符

作者: 阿啦啦啦啦啦 | 来源:发表于2019-02-20 09:14 被阅读0次

实现原理

通过 <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