扩展方法,设置文本框:
/*
* @param {Reg} reg 用来限制输入字符的格式,如位数,长度,取值范围等 */
1 $.fn.TextBoxThousandNumInput = function (reg) { 2 var obj = $(this); 3 var oldvalue = obj.val(); 4 var cursorPos = ""; 5 obj.keyup(function () { 6 var newvalue = obj.val(); 7 cursorPos = obj.getCursorPosition(); 8 if (newvalue == "") return obj; 9 newvalue = toNormalNum(newvalue); 10 if (!newvalue.match(reg)) { 11 obj.val(toThousands(oldvalue)); 13 } else { 14 obj.val(toThousands(newvalue)); 16 } 17 var offset=toThousands(newvalue).length-toThousands(oldvalue).length; 18 if ( offset < -1) { 19 setCursorPosition(this, cursorPos-1); 20 } else if (offset > 0) { 21 setCursorPosition(this, cursorPos+offset - 1); 22 } else { 23 setCursorPosition(this, cursorPos); 24 } 25 oldvalue =toNormalNum( obj.val()); 26 }); 27 return obj; 28 }
调用:
$(selector).TextBoxThousandNumInput (reg);
将数字转换为带有千位分隔符的数字:
1 var toThousands = function (num) { 2 var num = (num || '').toString(), re = /(d{3}|d{3}.d{0,2})$/, result = ''; 3 while (re.test(num)) { 4 result = RegExp.lastMatch + result; 5 if (num !== RegExp.lastMatch) { 6 result = ',' + result; 7 num = RegExp.leftContext; 8 } else { 9 num = ''; 10 break; 11 } 12 } 13 if (num) { result = num + result; } 14 return result; 15 }
将千位分割数字转换为普通数字:
1 var toNormalNum = function (numStr) { 2 return numStr.replace(/\,/g, ''); 3 }
设置文本区域光标位置:
/* * @param {HTMLInputElement/HTMLTextAreaElement} elem * @param {Number} index */ var setCursorPosition= function (elem, index) { var val = elem.value var len = val.length // 超过文本长度直接返回 if (len < index) return (function () { elem.focus() if (elem.setSelectionRange) { // 标准浏览器 elem.setSelectionRange(index, index) } else { // IE9- var range = elem.createTextRange() range.moveStart("character", -len) range.moveEnd("character", -len) range.moveStart("character", index) range.moveEnd("character", 0) range.select() } })(); }
获取输入框光标定位:
$.fn.getCursorPosition = function () { var el = $(this).get(0); var pos = 0; if ('selectionStart' in el) { pos = el.selectionStart; } else if ('selection' in document) { el.focus(); var Sel = document.selection.createRange(); var SelLength = document.selection.createRange().text.length; Sel.moveStart('character', -el.value.length); pos = Sel.text.length - SelLength; } return pos; }