1type="text" id="kahao"
1
123456789101112131415161718192021222324$(function() {$('#kahao').on('keyup', function(e) {//只对输入数字时进行处理if ((e.which >= 48 && e.which <= 57) ||(e.which >= 96 && e.which <= 105)) {//获取当前光标的位置var caret = this.selectionStart//获取当前的valuevar value = this.value//从左边沿到坐标之间的空格数var sp = (value.slice(0, caret).match(/\s/g) || []).length//去掉所有空格var nospace = value.replace(/\s/g, '')//重新插入空格var curVal = this.value = nospace.replace(/(\d{4})/g, "$1 ").trim()//从左边沿到原坐标之间的空格数var curSp = (curVal.slice(0, caret).match(/\s/g) || []).length//修正光标位置this.selectionEnd = this.selectionStart = caret + curSp - sp}})})