只能输入数值封装,input或者contentable==true的div,解决网上其他方法的bug,兼容移动端。


/**
 * 限制只能输入number
 * @param  {[type]} dom [限制的dom类名]
 */
function checkNumer(dom) {
        if (typeof $ == 'function') {
            let inp = $(dom);
            /**
             * 校验的正则
             * @param  {[type]} cdom [当前dom]
             */
            function viviNum(cdom) {
                let curvalue = '',
                    firststr = '';
                curvalue = $(cdom)[0].localName == 'input' ? cdom.value : cdom.innerText;
                curvalue = curvalue.toString();
                if (curvalue[0] == '-') {
                    firststr = '-';
                }
                let curindex = curvalue.indexOf('.');
                let curzero = curvalue.indexOf('0');
                if (curzero == 0) { //第一位是0
                    if (curvalue.length > 1) {
                        if (curvalue[curzero + 1] != '.') {
                            curvalue = '';
                        }
                    }
                }
                if (curindex >= 0) {
                    if (curindex == 0) {
                        let firstr = curvalue.substring(0, curindex + 1);
                        let newstr = curvalue.substring(curindex + 1);
                        firststr=firstr;
                        curvalue = newstr.replace(/\./g, '');   
                    } else {
                        if(curindex == 1&&curvalue[0]=='-'){
                            // curvalue=curvalue.split(".").join("");
                            curvalue='0.';
                        }
                        let firstr = curvalue.substring(0, curindex + 1);
                        let newstr = curvalue.substring(curindex + 1);
                        if (newstr.indexOf('.') >= 0) {
                            curvalue = firstr + newstr.substring(0, newstr.indexOf('.'));
                        } else {
                            curvalue = firstr + newstr;
                        }
                    }
                }
                if ($(cdom)[0].localName != 'input') {
                    cdom.innerText = (firststr=='.'?(0+firststr):firststr) + curvalue.replace(/[^\d\.]/g, '');
                } else { //input
                    cdom.value = (firststr=='.'?(0+firststr):firststr) + curvalue.replace(/[^\d\.]/g, '');
                }
            }
            inp.on({
                keyup: function() {
                    viviNum(this);
                },
                blur: function() {
                    viviNum(this);
                }
            });
        }
    }
//调用
checkNumer('.pt_teaching_box_right input');

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风儿轻丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值