服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - vue 限制input只能输入正数的操作

vue 限制input只能输入正数的操作

2021-08-06 16:48你眼中的柔情 JavaScript

这篇文章主要介绍了vue 限制input只能输入正数的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

在某些项目中 input 框只能输入数字,可以用以下办法:

先在标签上绑定上 @input 事件来监听标签的值变化,通过正则来改变输入的值。

?
1
2
3
4
5
6
7
<input
 class="keep_input"
 v-number-only
 style="width:35px"
 v-model="scope.row.fileOrder"
 @input="scope.row.fileOrder = Number($event.target.value.replace(/\D+/, ''))"
/>

第二部封装个自定义指令放在标签上!

?
1
2
3
4
5
6
7
8
9
10
11
12
13
directives: {
 numberOnly: {
  bind: function(el) {
   el.handler = function() {
    el.value = Number(el.value.replace(/\D+/, ''))
   }
   el.addEventListener('input', el.handler)
  },
  unbind: function(el) {
   el.removeEventListener('input', el.handler)
  }
 }
},

接下来就可以去页面看效果了,只能输入数字且只是正数!

附上 element 的 input 样式代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
.keep_input {
 -webkit-appearance: none;
 background-color: #fff;
 background-image: none;
 border-radius: 4px;
 border: 1px solid #dcdfe6;
 -webkit-box-sizing: border-box;
 box-sizing: border-box;
 color: #606266;
 display: inline-block;
 font-size: inherit;
 outline: 0;
 padding: 0 15px;
 -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
 transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
 height: 30px;
 line-height: 30px;
 text-align: left;
}
.keep_input:focus {
 border-color: #54a6de;
 outline: 0;
}

补充知识:记录el-input type=number限制长度el-input使用

如下所示:

?
1
2
3
4
5
6
<el-input type="number"
 oninput="if(value.length>10)value=value.slice(0,10)"
 @keyup.enter.native="query()"
 onKeypress="return(/[\d\.]/.test(String.fromCharCode(event.keyCode)))"
 :max="99999999">
 </el-input>

oninput 是个自定义事件 在事件里面获取输入的数字长度,来进行判断如果大于规定长度就进行剪切。

keyup.enter.native 是个键盘回车事件,当按下Enter键时触发query()事件。

max为输入框的最大值,如果input的type=number那么输入框内是输入不了字符的。

number框 解决输入e的问题

主要原因是:e在数学上代表的是无理数,是一个无限不循环的小数,其值约为2.7182818284,所以在输入e的时候,输入框会把e当成一个数字看待。

可以采用下面的方式来避免这个BUG,在input标签中添加如下属性:

onKeypress=“return(/[\d.]/.test(String.fromCharCode(event.keyCode)))”

<el-input placeholder="请输入密码" v-model="input" :show-password="true"></el-input>

show-password 加上这个属性输入字符进行隐藏一般用于密码框使用

记录问题!

以上这篇vue 限制input只能输入正数的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/return_js/article/details/95976604

延伸 · 阅读

精彩推荐