1.通过js原生方法实现:
1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
3. <head>
4. <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
5. <title>Document</title>
6. <script src="js/jQuery.js"></script>
7. </head>
8. <body>
9. <script>
10. num = 0;
11. function inputAccount(){
12.
13. str = $('#bankCard').val();
14.
15. elem = document.getElementById("bankCard");
16.
17. console.log(elem);
18.
19. > num){
20. c = str.replace(/\s/g, "");
21.
22. > 4 && c.length % 4 == 1){
23. $('#bankCard').val(str.substring(0, str.length - 1)+ " " + str.substring(str.length - 1, str.length));
24.
25. }
26. }
27.
28. if(elem.setSelectionRange){//W3C
29. setTimeout(function(){
30. elem.setSelectionRange(elem.value.length,elem.value.length);
31. elem.focus();
32. },0);
33. }else if(elem.createTextRange){//IE
34. textRange=elem.createTextRange();
35. textRange.moveStart("character",elem.value.length);
36. textRange.moveEnd("character",0);
37. textRange.select();
38. }
39.
40. num = str.length;
41.
42. }
43.
44. </script>
45.
46.
47. <input type="text" name="" oninput="inputAccount()" id="bankCard" />
48. </body>
49. </html>
2.通过jQuery实现:
1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
3. <head>
4. <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
5. <title>Document</title>
6. <script src="js/jQuery.js"></script>
7. </head>
8. <body>
9.
10.
11.
12. <input type="text" name="" id="box" />
13. <script>
14. $(function(){
15. $('#box').keyup(function(){
16. value=$(this).val().replace(/\s/g,'').replace(/(\d{4})(?=\d)/g,"$1 ");
17. $(this).val(value)
18. })
19. })
20. </script>
21. </body>
22. </html>
23. 第