通过键盘每个键的key值进行限制,在html代码使用事件οnkeydοwn="return validateDigitsOnly(event)"即可实现
1 /** 2 * 限制文本框只能输入数字 3 * @constructor 4 */ 5 function validateDigitsOnly(evt) { 6 var e = evt || window.event, 7 key = e.keyCode || e.which; 8 9 if (10 // Backspace, Tab, Enter, Esc, Delete11 key == 8 || key == 9 || key == 13 || key == 27 || key == 46 ||12 // Ctrl + A13 (key == 65 && event.ctrlKey === true) ||14 // Home, End, 四个方向键15 key >= 35 && key <= 40) {16 return;17 }18 19 if (e.shiftKey || e.altKey || e.ctrlKey) {20 return false;21 }22 23 var el = e.target || e.srcElement,24 // 最大数字长度25 nl = el.getAttribute("data-numbers") || 15,26 // 最大小数长度27 dl = el.getAttribute("data-decimals") || 2,28 val = el.value,29 // "." 位置30 dotIndex = val.indexOf("."),31 rng = caret.call(el),32 // 光标在"."左边33 rLeft = rng.end <= dotIndex,34 // 光标在"."右边35 rRight = rng.begin > dotIndex;36 37 if (38 // 数字39 key >= 48 && key <= 57 ||40 // 数字键盘输入的数字41 key >= 96 && key <= 105) {42 if (validateValue(dotIndex, val, rLeft, rRight, nl, dl))43 return;44 45 // 选中部分文本再做一次处理46 val = val.substring(0, rng.begin) + val.substring(rng.end);47 dotIndex = val.indexOf(".");48 if (validateValue(dotIndex, val, rLeft, rRight, nl, dl))49 return;50 }51 else if (52 // ".", ","53 (key == 190 /*|| key == 188*/ ||54 // 数字键盘上的 ".", ","55 key == 110/*|| key == 109*/) &&56 // 允许输入小数57 dl > 0) {58 if (59 // 未输入".", 且输入的位置后面的小数位数未达到上限60 dotIndex == -1 && (rng.end == val.length || val.substring(rng.end).length <= dl) ||61 // 输过".", 且选中部分文本包含"."62 dotIndex > -1 && rng.begin <= dotIndex && dotIndex < rng.end)63 return;64 }65 66 return false;67 }68 69 // 验证输入的值70 function validateValue(dotIndex, val, rLeft, rRight, nl, dl) {71 if (72 // 未输入过"."73 dotIndex == -1 && val.length < nl ||74 // 光标位置在"."之前75 rLeft && val.substring(0, dotIndex).length < nl ||76 // 光标在"."之后且未达到小数上限77 rRight && val.substring(dotIndex + 1).length < dl)78 return true;79 return false;80 }81 82 // 获取光标位置83 function caret() {84 var begin, end;85 if (this.setSelectionRange) {86 begin = this.selectionStart;87 end = this.selectionEnd;88 } else if (document.selection && document.selection.createRange) {89 var range = document.selection.createRange();90 begin = 0 - range.duplicate().moveStart('character', -100000);91 end = begin + range.text.length;92 }93 return { begin: begin, end: end };94 }