最近刚开始做小程序,有个需求是:用户输入兑换码时每四位用空格分隔,然后有焦点且有值时显示删除按钮,失焦点时隐藏删除按钮
话不多说先开始做,每四位用空格分隔简单:
给input标签绑定bindinput事件,然后在事件里处理
// wxml
<input type="text" value="{{activeCode}}" bindinput="codeInput" bindfocus="focusInput" bindblur="blurInput" placeholder="请输入兑换码"/>
<view class="clean" bindtap="clearInput">
<image class="{{clearShow ? 'show' : ''}}" src="../../common/images/index_clean.png" mode="widthFix"></image>
</view>
// js
codeInput: function(e) {
var str =value.replace(/\s/g,'').replace(/[^\w\.\/]/g,''); //移除输入框里的空格和特殊字符
var newCode = '';
if(str.length > 16) { // 限制输入长度
newCode =str.substr(0,16);
}else{
newCode = str;
}
newCode = newCode.replace(/\s/g,'').replace(/[^\w\.\/]/g,'').replace(/(\w{4})(?=\w)/g,"$1 "); // 每四位以空格分隔
// newCode.replace(/\s/g,'').replace(/[^\w\.\/]/g,'').replace(/(\w{4})(?=\w)/g,"$1-"); // 每四位以-分隔
if(str.length){
this.setData({
clearShow: true
})
}else{
this.setData({
clearShow: false
})
}
},
focusInput: function(){
var code = this.data.activeCode;
if(code.length){
this.setData({
clearShow: true
})
}
},
blurInput: function(){
var that = this;
setTimeout(function(){
that.setData({
clearShow: false
})
}, 200)
},
这时候遇到了一个问题,就是从中间删除或输入的时候,光标会置后,跑到最后面...
解决办法:
利用input标签的cursor属性
input value和cursor不能用setData赋值,用return
// wxml
<input type="text" value="{{activeCode}}" bindinput="codeInput" bindfocus="focusInput" bindblur="blurInput" placeholder="请输入兑换码" cursor="{{cursor}}" />
// js
codeInput: function(e) {
var value = e.detail.value;
var pos = e.detail.cursor;
var str =value.replace(/\s/g,'').replace(/[^\w\.\/]/g,'');
var newCode = '';
if(str.length > 16) {
newCode =str.substr(0,16);
}else{
newCode = str;
}
var posAfterText = "";
var posPreText = "";//前面的是否是空格
var isNextBlank = false;//后面的是否是空格
var isPreBlank = false;
var isLastPos = true;
if (pos != value.length) {//不是最后一个
posAfterText = value.substr(pos, 1);
posPreText = value.substr(pos - 1, 1);
isNextBlank = /^\s+$/.test(posAfterText);
isPreBlank = /^\s+$/.test(posPreText);
isLastPos = false;
}
newCode = newCode.replace(/\s/g,'').replace(/[^\w\.\/]/g,'').replace(/(\w{4})(?=\w)/g,"$1 ");
if(e.detail.keyCode == 8){
if(str.length){
this.setData({
clearShow: true
})
this.data.activeCode = newCode
return {
value: newCode,
cursor: e.detail.cursor,
}
}else{
this.setData({
clearShow: false
})
this.data.activeCode = newCode
return {
value: newCode,
cursor: e.detail.cursor,
}
this.data.activeCode = newCode
}
}else{
this.data.activeCode = newCode
if(str.length){
if (!isLastPos) {
if (isNextBlank) {
this.setData({
clearShow: true,
})
return {
value: newCode,
cursor: pos+1
}
} else {
this.setData({
clearShow: true,
})
return {
value: newCode,
cursor: pos
}
}
} else {
this.setData({
clearShow: true,
})
return {
value: newCode,
cursor: pos+1
}
}
} else {
this.setData({
clearShow: false
})
return {
value: newCode,
cursor: pos+1
}
}
}
},