input 聚焦掉起键盘,并且只能输入数字
2018-03-08 17:17
246 查看
input 聚焦掉起键盘,并且只能输入数字
问题描述
在实际项目开发中,会有需求为 input 聚焦掉起键盘,并且只能数字,开发者第一反应为 type 修改 number,但是 number 是允许输入 + - . e 四个字符的,以下是项目中的解决思路;解决方案
1.方法一:<template> <input type="number" placeholder="请输入手机号" name="phone" @keypress="onKeyPress()" v-model="phoneMessage" :class="{'hasContent':phoneMessage.length>0}" > </template> <script> onKeyPress () { event.returnValue = /[\d]/.test(String.fromCharCode(event.keyCode)); } </script>
以上方法在 pc 端可以,但是移动端 keypress 不会触发(移动端会触发 keyon 和 keydown),并且移动端输入小数点之后, phoneMessage 会变为空,所以不太完善。
2.方法二
<template> <input type="number" placeholder="请输入手机号" name="tel" @input="onInput()" v-model="phoneMessage" :class="{'hasContent':phoneMessage.length>0}" > </template> <script> onInput () { let content = this.phoneMessage.split("").filter( (item,index) => { return /^[0-9]*$/.test(item) && index < 11; }).join(""); this.phoneMessage = content; } </script>
这种方案思路是将 input type 变为 tel,这样,在移动端只能掉起数字键盘,并且输入其他字符时,也能正常触发 input 事件,然后通过 js 来截取所需要的内容(京东的登录也是这种方案);
相关文章推荐
- EditText设置弹出数字键盘,并且只能输入数字和.
- android 只能输入数字和字母并且弹出数字键盘
- JQuery:在input中只能输入数字,并且不能复制粘贴,不能切换输入法
- javascript 控制input只能输入数字并且最多允许两位小数的数字
- JQuery:在input中只能输入数字,并且不能复制粘贴,不能切换输入法
- HTML中input只能输入数字(键盘抬起和粘贴事件)
- JQuery:在input中只能输入数字,并且不能复制粘贴,不能切换输入法
- input只能输入数字和小数点,并且只能保留小数点后两位
- android 只能输入数字和字母并且弹出数字键盘
- JQuery:在input中只能输入数字,并且不能复制粘贴,不能切换输入法
- input中只能输入数字
- 如何限制input只能输入数字
- js控制input文本框只能输入数字
- 简单自定义安全键盘(只能输入字母,数字,部分符号)
- INPUT只能输入数字
- Input 只能输入数字,数字和字母等的正则表达式
- input标签只能输入数字js实现(且不能输入e或者其他各种符号)
- 使用正则限制input框只能输入数字/英文/中文等等
- 移动端手机网站限制input只能输入数字
- Event.keyCode控制input只能输入数字