基于Vant-NumberKeyboard的自定义数字输入框 + 数字键盘
custom-input
基于Vant-NumberKeyboard的自定义数字输入框
问题产生背景
- 移动端项目中需要用到数字输入框,html 自带的 input 标签设置[type=number]会默认调用系统输入法的数字键盘,可这样的话,minlength、maxlength 等属性就失效了,还无法禁止部分特殊字符的输入
- 利用 input 自带的 change 或者 input 事件在 js 进行判断,会导致 input 内造成闪动效果,光标会默认跑到尾部(可控制光标,兼容性不是很好)
- IOS 可利用 keypress 进行输入前的判断,Android 却不支持该事件,迫于无奈只能手动实现数字输入框 input
效果预览

模拟光标实现原理

1 | .cursor { |
use 使用
在 main.js 中引入组件
1 | import customInput from "./components/customInput"; |
接下来,你就可以在页面中使用 custom-input 了
1 | <template> |
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| value | 当前输入的值 | String | - |
| placeholder | 自定义 input 框占位符 | String | placeholder |
| transform | 是否判断自定义 input 位置被自定义键盘覆盖 | Boolean | true |
| max | 自定义 input 最大值设置 | String, Number | 9999999999.99 |
| toFixed | 小数点后保留位数 | Number | 2 |
| 事件 | 说明 | 返回值 |
|---|---|---|
| onKeyboardOpen | 自定义键盘展开事件 | data |
| close | 自定义键盘关闭事件 | data |
| input | 当前输入值改变时间 | data |
文件目录
1 | . |
相关代码: