效果
wxml
<!-- components/identifyingCode/identifyingCode.wxml -->
<view class="flex a-c j-c">
<view class='content' style="width:{{90 * Length + 'rpx'}};background:{{errVisble?'#ffd9d9':''}}">
<block wx:for="{{Length}}" wx:key="item">
<input type="number" class='iptbox' value="{{Value.length>=index+1?Value[index]:''}}" disabled password='{{ispassword}}' catchtap='Tap' style=" border-right:{{index + 1 != Length? '0.5rpx solid #e3e3e3': '0rpx solid #e3e3e3'}};"></input>
</block>
</view>
</view>
<view class="flex a-c j-c">
<text wx:if="{{errVisble}}" style="color:red" class="errMsg">{{errMsg}}</text>
</view>
<input name="password" type="number" password="{{true}}" class='ipt' maxlength="{{Length}}" focus="{{isFocus}}" bindinput="Focus"></input>
wxss
/* components/identifyingCode/identifyingCode.wxss */
.content {
display: flex;
align-items: center;
justify-content: center;
border: 1rpx solid #999999;
border-radius: 16rpx;
}
/* 显示的input */
.iptbox {
width: 90rpx;
height: 90rpx;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
}
/* 不可见的input */
.ipt {
width: 0;
height: 0;
}
.errMsg{
margin-top: 20rpx;
font-size:30rpx;
}
json
{
"component": true,
"usingComponents": {}
}
js
// components/identifyingCode/identifyingCode.js
Component({
options: {
addGlobalClass: true
},
/**
* 组件的属性列表
*/
properties: {
//输入框个数
Length:{
type: Number,
value: 4
},
//是否密文显示 true为密文, false为明文。
ispassword:{
type: Boolean,
value: false,
},
//错误提示
errMsg:{
type: String,
value: "错误",
},
//错误提示可见性
errVisble:{
type: Boolean,
value: false,
}
},
/**
* 组件的初始数据
*/
data: {
isFocus:true, //聚焦
Value:"", //输入的内容
},
/**
* 组件的方法列表
*/
methods: {
Focus(e){
var that = this;
console.log(e.detail.value);
var inputValue = e.detail.value;
that.setData({
Value:inputValue,
})
//输入达到指定长度
if(inputValue.length == this.data.Length){
this.triggerEvent('codeChange', { code: this.data.Value });
}
//删除字符
if(inputValue.length < this.data.Length && this.data.errMsg ){
that.setData({
errVisble:false
})
}
},
Tap(){
var that = this;
that.setData({
isFocus:true,
})
},
}
})