js input框限制输入为数字并限制长度

HTML&CSS 1年前 (2021) 小马大哥哥
135 0
// 只能输入数字 且 长度为<=10   
<input type="number" name="price" id="priceVal" placeholder="请输入价格" oninput="if(value.length>10)value=value.slice(0,10)"/>

这样写是有问题的,原生input,type=number  是可以输入e + – .这些字符的,如果需要只能输入数字,需要这样写:

<input onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
type="number" placeholder="请输入"/>

input的type为number类型之后,输入框的右侧会默认有上下箭头,去除默认箭头css样式代码如下:

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input[type="number"]{
-moz-appearance: textfield;
}
// vue的scope下
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
/deep/ input[type="number"]{
-moz-appearance: textfield;
}

 

版权声明:小马大哥哥 发表于 2021-12-08 16:15:37。
转载请注明:js input框限制输入为数字并限制长度 | 马哥导航

暂无评论

暂无评论...