input输入框4位一个空格,模拟银行卡号输入

<!doctype html> <html> <head> <meta charset="utf-8"> <title>银行卡四位空格</title> <script src="http://libs.baidu.com/jquery/1.11.3/jquery.mi...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>银行卡四位空格</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
</head>
<body>
<input type="text" id="kahao">

<script>
 $(function() {
     $('#kahao').on('keyup', function(e) {
         //只对输入数字时进行处理
         if ((e.which >= 48 && e.which <= 57) ||
             (e.which >= 96 && e.which <= 105)) {
             //获取当前光标的位置
             var caret = this.selectionStart
             //获取当前的value
             var 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
         }
     })
 })
</script>
</body>
</html>

attachments-2020-06-6KBOB4Tm5ef6c7e55354c.png

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
admin
admin

651 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. Stevengring 0 文章