@Wangww0925
2019-08-07T07:57:20.000000Z
字数 1715
阅读 183
js
/**
* 控制input输入只能为数字
* 一般用于输入手机号 密码
* 参数
dom input元素
keyup keyup事件 回调
* 调用
NumKeyEvent($(".input"),function (that) {
console.log("keyup")
})
*/
function NumKeyEvent(dom,keyup){
// 鼠标抬起时过滤额不是数字的内容
dom.keyup(function () {
var reg = $(this).val().match(/\d*/);
var txt = reg ? reg[0] : "";
$(this).val(txt.trim())
keyup && keyup(this);
})
}
/**
* 控制input输入只能为数字和 .
* 参数
dom input元素
number 小数位数,(默认2位数)
keyup keyup事件 回调
change change事件 回调
blur blur事件 回调
focus focus事件 回调
* 注意 : 使用该函数需要在input定义 amount 属性 ,该方法的而数据以 input的amount属性值为准
* 调用
bindKeyEvent($(".input"),number, function (that) {
/* console.log("keyup") */
},function (that) {
/*console.log("change")*/
},function (that) {
/*console.log("blur")*/
},function (that) {
/*console.log("focus")*/
})
*/
function bindKeyEvent(dom,number,keyup,change,blur,focus){
checkDataInput(number) ? number : number = 2
dom.focus(function(){ // 触发焦点时让其值为数字格式
var amount = $(this).attr("amount");
if(!amount){
var val = parseFloat($(this).val()).toFixed(number);
if(val != "" && !isNaN(val)){
$(this).attr("amount",val);
amount = val
}
}
$(this).val(amount);
focus ? focus(this) : ""
}).keyup(function () { // 鼠标抬起时过滤额不是数字的内容
var reg = new RegExp("\\d+" + (number > 0 ? '\\.?' : '' ) + "\\d{0," + number + "}")
// var reg = $(this).val().match(/\d+\.?\d*/); // 小数位数不限
var match = $(this).val().match(reg);
var txt = match ? match[0] : "";
$(this).val(txt.trim())
keyup ? keyup(this) : ""
}).change(function () { // 当内容改变时
var val = $(this).val();
if (/\.$/.test(val)){
$(this).val(val.substr(0, val.length - 1));
}
change ? change(this) : ""
}).blur(function () {
var value = parseFloat($(this).val()) == 0 ? "" : parseFloat($(this).val()).toFixed(number);
isNaN(value) ? value = "" : "";
$(this).val(String(value)).attr("amount",String(value));
blur ? blur(this) : ""
})
}
作者 wendy
2019 年 6月 5日