<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <title></title> <script src="jquery-1.10.1.min.js" ></script> </head> <body> <input type="text" id="alterNumber" style="width: 300px;"/> <script> $(function() { //The difficulty is not to insert spaces, but to correct the position of the cursor, this only supports IE9+ // can be used for bank card number $('#alterNumber').on('keyup', function(e) { // process only when entering numbers if((e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105 )){ //Get the current cursor position var caret = this.selectionStart; //get the current value var value = this.value; //Number of spaces from the left edge to the coordinates var sp = (value.slice(0, caret).match(/\s/g) || []).length; // remove all spaces var nospace = value.replace(/\s/g, ''); // reinsert spaces var curVal = this.value = nospace.replace(/(\d{4})/g, "$1 ").trim(); //Number of spaces from the left edge to the original coordinate var curSp = (curVal.slice(0, caret).match(/\s/g) || []).length; //correct cursor position this.selectionEnd = this.selectionStart = caret + curSp - sp; } }) }) </script> </body> </html>
Effect picture:
Reference source: http://www.cnblogs.com/rubylouvre/p/6087353.html