微信小程序倒计时功能 可以用于短信验证码的倒计时等
方法1.
Js:
function countdown(that) {
var second = that.data.countdown_time
if(second == 0) {
console.log("001");
// console.log("Time Out...");
that.setData({
// second: "Time Out..."
showtime1: true,
showtime2: false,
reg_hqyzm: "重新获取",
countdown_time:5,
});
console.log("002");
return;
}
console.log("003");
var time = setTimeout(function () {
that.setData({
countdown_time: second - 1
});
countdown(that);
}
, 1000)
}
Page({
/**
* 页面的初始数据
*/
data: {
showtime1: true,
showtime2: false,
reg_hqyzm: "获取验证码",
countdown_time: 5,
},
reg_yanzhengma_huoqu:function(){
console.log("004");
this.setData({
showtime1: false,
showtime2: true,
});
countdown(this);
// wxTimer.start(this);
},});
wxml:
<view class="reg_yanzhengma">
<image class="img_yanzhenma" src="https://img-blog.youkuaiyun.com/20170527164756495?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvVUZPMDAwMDE=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center"></image>
<input class="input_reg_yanzhengma" bindconfirm="input_reg_yanzhengma" placeholder="请输入验证码" type="number"/>
<view wx:if="{{showtime1}}" class="reg_yanzhengma_time1" bindtap="reg_yanzhengma_huoqu">
{{reg_hqyzm}}
</view>
<view wx:if="{{showtime2}}" class="reg_yanzhengma_time2" >
倒计时:{{countdown_time}}s
</view>
</view>
wxss:
.reg_yanzhengma{
width: 100%;
height:100rpx;
margin-top: 10rpx;
display: flex;
background: #fff
}
.img_yanzhenma{
width: 10%;
height:60rpx;
margin-top: 20rpx;
margin-left: 50rpx;
}
.input_reg_yanzhengma{
width: 55%;
height:50rpx;
margin-top: 20rpx;
margin-left: 50rpx;
font-size: 28rpx;
}
.reg_yanzhengma_time1{
width: 35%;
height:100%;
margin-left: 50rpx;
font-size: 30rpx;
background: #0f0;
line-height: 100rpx;
text-align: center;
color: #fff;
}
.reg_yanzhengma_time2{
width: 35%;
height:100%;
margin-left: 50rpx;
font-size: 30rpx;
background: #777777;
line-height: 100rpx;
text-align: center;
color: #fff;
}
方法2. wxTimer 稍后再写