vue重置input光标位置, 在input输入加入空格,光标实时监听出错
vue中手机输入加入空格 123 **** 7894 形式,在一些手机光标会在输入的前一个显示
手机加入空格
watch: {
phone: function (value) {
let newValue = value.replace(/\D/g, '').substring(0, 11)
const valueLen = newValue.length
if (valueLen > 3 && valueLen < 8) {
newValue = `${newValue.substr(0, 3)} ${newValue.substr(3)}`
} else if (valueLen >= 8) {
newValue = `${newValue.substr(0, 3)} ${newValue.substr(3, 4)} ${newValue.substr(
7
)}`
}
this.phone = newValue
setTimeout(() => {
this.$refs.phone.setSelectionRange(this.phone.length, this.phone.length);
}, 20)
},
}
解决:
获取input框,利用input框的setSelectionRange进行重置光标
setTimeout(() => {
this.$refs.phone.setSelectionRange(this.phone.length, this.phone.length);
}, 20)
网友评论