美文网首页
微信小程序-验证码倒计时

微信小程序-验证码倒计时

作者: HCL黄 | 来源:发表于2019-11-14 11:49 被阅读0次

如图

2222.gif

代码很少,都有注释,话不多说,直接上代码

<!--index.wxml-->
<view class="center">
  <view class="cntV {{codeTimeing?'cntV-gray':''}}" 
        bindtap="didClickGetCode">
    <text class="cntV-text">{{codeDesc}}</text>
  </view>
</view>
/**index.wxss**/
.center {
  display: flex;
  align-items: center;
  justify-content: center;

  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.cntV {
  width:186rpx;
  height:88rpx;
  background:rgba(235,202,144,1);

  display: flex;
  align-items: center;
  justify-content: center;
}
.cntV-gray {
  background:rgba(153,153,153,1);
  opacity:0.5;
}
.cntV-text {
  font-size:28rpx;
  font-family:PingFang-SC-Bold,PingFang-SC;
  font-weight:bold;
  color:rgba(255,255,255,1);
  line-height:40rpx;
}
//index.js
const StaticSeconds = 5

Page({
  data: {
    seconds: StaticSeconds,
    codeTimer: null, // 验证码倒计时
    codeDesc: '获取验证码', // 验证码按钮文案
    codeTimeing: false, // 验证码倒计时是否正在倒计时
  },
  onLoad: function () {
    
  },
  // 重置倒计时
  resetTimer: function () {
    var that = this;
    // 清除倒计时
    clearInterval(that.data.codeTimer)
    that.setData({
      seconds: StaticSeconds,
      codeTimeing: false,
      codeDesc: '获取验证码', // 验证码按钮文案
    })
  },
  // 点击获取验证码
  didClickGetCode: function () {
    var that = this;

    if (that.data.codeTimeing) { // 正在倒计时
      console.log('正在倒计时')
      return;
    }
    console.log('开始倒计时')
    
    // 修改状态及文案
    that.setData({
      codeTimeing: true,
      codeDesc: that.data.seconds + 's', // 验证码按钮文案
    })

    // 开启倒计时并保存倒计时对象
    that.data.codeTimer = setInterval(function () {
      var div = that.data.seconds - 1;
      if (div <= 0) { // 倒计时完了之后重置
        that.resetTimer();
        return;
      }
      var codeStr = div + 's';
      that.setData({
        seconds: div,
        codeDesc: codeStr, // 验证码按钮文案
      })
    }, 1000)
  },
})

相关文章

网友评论

      本文标题:微信小程序-验证码倒计时

      本文链接:https://www.haomeiwen.com/subject/elfrictx.html