Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

输入框输入值自动格式化 #7

Open
LoeiFy opened this issue Apr 28, 2015 · 3 comments
Open

输入框输入值自动格式化 #7

LoeiFy opened this issue Apr 28, 2015 · 3 comments
Milestone

Comments

@LoeiFy
Copy link
Owner

LoeiFy commented Apr 28, 2015

这里说的自动格式化是指当用户在输入框里面输入数字,例如银行卡号,为了方便用户输入,希望在输入过程中对输入数字进行加空格处理,优化用户体验

先看一下例子: http://jsfiddle.net/am0200/qugp8tvL/

注意例子里面的输入框的类型是 tel,而不是 number,主要原因是 number 类型

  • 会导致 Android 上某些系统不显示 placeholder
  • 无法插入非数字内容,例如空格

代码实现

data-gap 代表第几位开始加空格,不为 0

<input data-gap=4 maxlength="24" size="30" autocomplete="off" type="tel" placeholder="请输入卡号"/>

原理就是获取用户输入内容,格式化处理完成后再填入输入框

var input = document.querySelectorAll('input')[0]
var gap = parseInt(input.getAttribute('data-gap'))

input.oninput = function() {
  var numbers = this.value.replace(/\s+/g, '').split('')     // 获取原始值
  var back = '' 

  numbers.forEach(function(n, i) {
    back += n + ((i + 1) % gap === 0 ? ' ' : '')    // 处理加空格
  })
  
  var len = back.length
  var last = back.charAt(len - 1)

  if (last === ' ' || isNaN(last)) {
    back = back.substring(0, len - 1)    // 移除末尾无用字符
  }

  this.value = back
  
  // 兼容处理
  setTimeout(function() {
    this.setSelectionRange(len, len)
    this.focus()
  }.bind(this), 0)
}

获取输入原始值

input.value.replace(/\s+/g, '')

扩展

可以设置格式化分割字符,例如用 - 代替空格,还可以设定不规则位数空格,具体可以修改处理条件即可

@LoeiFy
Copy link
Owner Author

LoeiFy commented Apr 28, 2015

这是一种方式,可能可以使用正则方式来做,具体没有试验过

@LoeiFy LoeiFy changed the title 移动端支付输入用户体验,充值卡卡号密码输入过程添加空格 移动端充值卡输入用户体验,卡号密码输入过程自动添加空格 Jan 14, 2016
@LoeiFy LoeiFy closed this as completed Dec 19, 2016
@LoeiFy LoeiFy changed the title 移动端充值卡输入用户体验,卡号密码输入过程自动添加空格 输入框输入值自动格式化 Apr 11, 2017
@LoeiFy LoeiFy reopened this Apr 11, 2017
@LoeiFy LoeiFy added this to the blog milestone Dec 16, 2017
@LikeDege
Copy link

从中间删除插入数字时,光标会跳到字符串的最后,是否有解决办法

@LoeiFy
Copy link
Owner Author

LoeiFy commented Dec 18, 2017

应该可以的,你判断一下输入位置,然后对应设置相应选择位置

_this.setSelectionRange(3, 3)
_this.focus()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants