我已经调整了您的代码以在TextBox(输入类型=“text”)中工作,这样我们就可以在不丢失光标的情况下实时输入和删除数字。如果您在删除时选择范围,它也会起作用。您可以自由使用箭头和起始/结束按钮。谢谢你节省了我的时间!
//function controls number format as "1,532,162.3264321"
function numberWithCommas(x) {
var e = e || window.event;
if (e.keyCode >= '35' && e.keyCode <= '40') return; //skip arrow-keys
var selStart = x.selectionStart, selEnd = x.selectionEnd; //save cursor positions
var parts = x.value.toString().split(".");
var part0len = parts[0].length; //old length to check if new ',' would be added. Need for correcting new cursor position (+1 to right).
//if user deleted ',' - remove previous number instead (without selection)
if (x.selectionLength == 0 && (e.keyCode == 8 || e.keyCode == 46)) {//if pressed 8-backspace or 46-delete button
var delPos = parts[0].search(/\d{4}/);
if (delPos != -1) {//if found 4 digits in a row (',' is deleted)
if (e.keyCode == 8) {//if backspace flag
parts[0] = parts[0].slice(0, selStart - 1) + parts[0].slice(selEnd, parts[0].length);
selEnd--;
if (selStart > selEnd) selStart = selEnd;
} else {
parts[0] = parts[0].slice(0, selStart) + parts[0].slice(selEnd + 1, parts[0].length);
selStart++;
if (selEnd < selStart) selEnd = selStart;
}
}
}
var hasMinus = parts[0][0] == '-';
parts[0] = (hasMinus ? '-' : '') + parts[0].replace(/[^\d]*/g, ""); //I'd like to clear old ',' to avoid things like 1,2,3,5,634.443216
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); //sets ',' between each 3 digits
if (part0len < parts[0].length) { //move cursor to right if added new ','
selStart++;
selEnd++;
} else if (part0len > parts[0].length) { //..or if removed last one ','
selStart--;
selEnd--;
}
x.value = parts.join(".");
x.setSelectionRange(selStart, selEnd); //restoring cursor position
}
function saveSelectionLength(x) {
x.selectionLength = x.selectionEnd - x.selectionStart;
}
要使用它,只需添加两个事件-onKeyUp和onKeyDown
<asp:TextBox runat="server" ID="val" Width="180px" onKeyUp="numberWithCommas(this);" onKeyDown="saveSelectionLength(this);"/>