微信小程序实现无光标验证码功能

2,141 阅读4分钟
0. 写在前面
一位小伙伴有一天突然的问我,微信小程序中的填写验证码的框框怎么去写,我说这个简单啊,6个输入框不就搞定了,他说他实在是不会,问我可不可以帮他写一个demo,我当时想的是这么简单的东西还用问?就回复有时间就帮你写好了。于是,我真的有时间,也真的写了demo,不过,这个看起来简单的案例并没有想象的那么简单。




这是我做出的效果图


上图的效果在他问问题之前我就想到了,起码静态页面我三下五除二的就写完了,可是在真正写逻辑交互的时候出现了很多的问题。尽管微信小程序的input有很多的功能,但是在真机调试的时候,最大的问题就是,切换input的时候,键盘一直在打开收回。我们都知道,在移动端输入验证码的时候,输入法是不会收回的,但是我们这里用了6个输入框,在失去focus的时候,键盘是自动收回的。为了解决这个问题,我重新思考了一下。
1. 静态结构思路
在上一个小节,我们遇到了一个史诗级的bug,就是输入法会在失去焦点的时候反复的弹出收回,非常恶心的bug。
那么现在我们只要考虑怎样才能不让输入法收回?
那就是input不失去焦点的时候。
但是我们为了美观,6位的验证码我们又要分成6个单独的输入框。
所以,我们索性就再在页面上写一个input,专门存储这段完整的验证码。
然后把它隐藏起来,再根据这个输入框中的内容,动态的渲染到上面6个输入框中。
按照这个结构,我们的代码是这个样子的~
[XML]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
<view class='container'>
<form bindsubmit="submitCode">
<view class='title'>请输入验证码</view>
<view class='indentify-code'>
<block wx:for="{{codeLength}}" wx:key="index">
<input class='code-box' password="{{isPass}}" catchtap='focusBox' value='{{code.length>=1?code[index]:""}}' disabled></input>
</block>
</view>
<input class='realCode' type="{{type}}" password="{{isPass}}" focus="{{isFocus}}" bindinput="inputCode" maxlength='{{codeLength}}' name="code" type='num'></input>
<button formType="submit" class='submit'>提交</button>
</form>
</view>
[CSS]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
.title{
color: #555;
font-size: 36rpx;
padding-left: 20rpx;
margin-bottom: 20rpx;
}
.indentify-code{
display: flex;
justify-content: space-around;
}
.indentify-code .code-box{
width: 80rpx;
height: 80rpx;
border: 1px solid #999;
border-radius: 20rpx;
text-align: center;
}
.realCode{
width: 0px;
height: 0px;
}
.submit{
width: 60%;
height: 100rpx;
color: #fff;
line-height: 100rpx;
text-align: center;
border-radius: 20rpx;
background-color: lightskyblue;
margin: 0 auto;
}

效果图如上
2. js思路
这里就非常的简单了,我们只要给上面的所有的单个输入框一个点击事件,当点击时候,就让那个看不见的input一个焦点,然后我们输入的内容,都是放在这个看不见的input框中。我们上面的value就可以动态的通过我们输入的值,去渲染出来就可以了。
然后再做一个没有输入完全的时候,一个提示信息。
[AppleScript]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
Page({[/size][/font][/color][/align]
/**
* 页面的初始数据
*/
data: {
codeLength: 6,
type: 'number',
isPass: false,
isFocus: true,
code: ''
},
focusBox(){
this.setData({
isFocus: true
})
},
inputCode(e){
this.setData({
code: e.detail.value
})
},
submitCode(e){
if (e.detail.value.code.length<this.data.codeLength){
wx.showToast({
title:'验证码没有填全哦~',
icon: "none",
duration: 1500
})
}else{
wx.showToast({
title: '登录成功',
duration: 1500
})
}
console.log(e.detail.value.code.length)
}
}
)

更多技术资讯可关注:gzitcast