应用场景:
微信小程序手机验证页面,输入手机号码,点击“获取验证码”之后出现的“60s之后重新获取”
案例效果图:
实现说明:
点击“获取验证码”按钮,按钮变成“60s之后重新发送”,然后,在用定时器,判断当时间小于1,低于60s的时候,按钮重新变成“获取验证码”。
1.利用css来进行按钮的切换
//wxml
<button class="{{gettime?'disblock':' '}}" size='mini' bindtap='gettimes'>获取验证码</button>
<button class="{{gettime?' ':'disblock'}}" size='mini' >{{counts}}s后重新发送</button>
//利用css的display来显示隐藏按钮。使用三元运算进行简单的判断
js:
data: {
gettime:false,
counts:60
},
gettimes:function(){
var that = this;
that.setData({
gettime:true
});
//倒计时主要部分,利用定时器
var getsix = setInterval(function(){
var times = that.data.counts-1;
that.setData({
counts:times
});
if (that.data.counts < 1){
clearInterval(SetCount);
that.setData({
gettime: false,
counts:60
})
}
},1000);
}
2.利用if判断按钮的出现
wxml:
<view>
<button wx:if="{{GetCount}}" size="default" hover-class="other-button-hover" bindtap="Clicktap">点击发送验证码</button>
<button wx:if="{{!GetCount}}" type="default" size="default" disabled="true">{{counts}}s后重新发送</button>
</view>
js:
data: {
GetCount:true,
counts:60
},
Clicktap:function(){
var that = this;
if(tel == ''){
//判断是否填写手机号码
}else{
//倒计时主要部分,利用定时器
that.setData({
GetCount:false
})
var SetCount = setInterval(function(){
var times = that.data.counts-1;
that.setData({
counts:times
});
if (that.data.counts < 1){
clearInterval(SetCount);
that.setData({
GetCount: true,
counts:60
})
}
},1000);
}
}
我的难点:
1.取60s的counts的值,使用that.data.counts来表示,前提是我在函数前用了(var that = this)
2.判断的时候,假如counts小于1,按钮变化了之后(gettime的值变化),counts的值应该重新设定60;