js格式化input输入框内容(每几位分一组,并使用特定字符分隔)

时间:2022-04-14 20:57:14
<html>
<head>
<title></title>
</head>
<body> <input id="inputDom" /> <script type="text/javascript">
var inputDom = document.getElementById('inputDom');
var maxLen = 0;
inputDom.oninput = function() {
var value = this.value;
var valueLen = value.length;
var foucsNum = getCursortPosition(inputDom);
if(valueLen > 0){
var c = value.replace(/\s/g, "");
var Len = c.length;
var List = c.split('');
var initNum = 0;
for(var i=1;i<Len;i++) {
if(i%4 == 0) {  //每四位分一组
List.splice(i+initNum,0,' ');  //此处为使用空格分隔
initNum++
}
}
this.value = List.join(''); if(maxLen < this.value.length) {
if(foucsNum%5 == 0) {
setTimeout(function() {
setCaretPosition(inputDom,foucsNum+1)
},0);
}else {
setTimeout(function() {
setCaretPosition(inputDom,foucsNum)
},0);
}
}else {
if(foucsNum%5 == 0) {
setTimeout(function() {
setCaretPosition(inputDom,foucsNum-1)
},0);
}else {
setTimeout(function() {
setCaretPosition(inputDom,foucsNum)
},0);
}
}
maxLen = this.value.length;
}
}
     //控制光标移动时,需要使用定时器,避免出现光标控制失效的情况
function getCursortPosition(ctrl) { //获取光标的位置
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
} function setCaretPosition(ctrl, pos) { //设置光标的位置
if(ctrl.setSelectionRange){
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>
</body>
</html>

  如果以上代码无法满足业务需要,可以使用插件Cleave.js,进行input框中数据的格式化;