只能輸入數值封裝,input或者contentable==true的div,解決網上其他方法的bug,相容移動端。
阿新 • • 發佈:2018-11-30
/** * 限制只能輸入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');