input校驗只能輸入正負小數封裝,適用於移動端。
阿新 • • 發佈:2018-12-10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>校驗</title> </head> <body> <input id="id1" class="ah" type="text" /> <input id="id1" class="ah" type="text" /> </body> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script> checkNumer('.ah'); /** * 限制只能輸入number * @param {[type]} dom [限制的dom類名] */ function checkNumer(dom) { let inp = $(dom); /** * 校驗的正則 * @param {[type]} cdom [當前dom] */ function viviNum(cdom) { let curvalue = '', firststr = ''; if (cdom.value[0] == '-') { firststr = '-'; } curvalue = cdom.value; let curindex = curvalue.indexOf('.'); let curzero = curvalue.indexOf('0'); if (curzero == 0) { //第一位是0 console.log(curzero); if (curvalue.length > 1) { if (curvalue[curzero + 1] != '.') { cdom.value = ''; } } } if (curindex >= 0) { if (curindex == 0) { cdom.value = ''; } else { let firstr = curvalue.substring(0, curindex + 1); let newstr = curvalue.substring(curindex + 1); if (newstr.indexOf('.') >= 0) { cdom.value = firstr + newstr.substring(0, newstr.indexOf('.')); } else { cdom.value = firstr + newstr; } } } cdom.value = firststr + cdom.value.replace(/[^\d\.]/g, ''); } inp.on({ keyup: function() { viviNum(this); }, blur: function() { viviNum(this); } }); } </script> </html>