js实现手机号输入框中间空格效果

效果如下:

具体实现如下:

1
<input type="tel" class="phone" v-model="phoneText" @keydown="keyDown" @keyup.delete="keyUp" maxlength="13">

1
2
3
4
5
6
7
8
9
keyDown (e) { // 按下时判断在指定位置添加空格
if (e.keyCode !== 8 && (this.phoneText.length === 3 || this.phoneText.length === 8)) {
this.phoneText += ' '
}
},
keyUp () { // 删除键抬起后清楚结尾空格
// 非vue写法 if (e.keyCode === 8) {}
this.phoneText = this.phoneText.replace(/\s*$/g, '')
}

如果想要初始化赋值:

1
2
3
this.phoneText = this.phoneText
.replace(this.phoneText.substr(2, 1), this.phoneText.substr(2, 1) + ' ')
.replace(this.phoneText.substr(6, 1), this.phoneText.substr(6, 1) + ' ')