1. 程式人生 > >微信小程式60秒倒計時

微信小程式60秒倒計時

微信小程式傳送簡訊驗證碼後60秒倒計時功能,效果圖:

 

完整程式碼

index.wxml

<!--index.wxml-->
<view class="container">
  <view class="section">
    <text>手機號碼:</text>
        <input placeholder="請輸入手機號碼" type="number" maxlength="11" bindinput="inputPhoneNum" auto-focus />
        <text wx:if="{{send}}" class="sendMsg" bindtap="sendMsg">傳送</text>
        <text wx:if="{{alreadySend}}" class="sendMsg" >{{second+"s"}}</text>
    </view>
</view>

  

index.wxss

/**index.wxss**/
.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.section {
display: flex;
margin: 16rpx;
padding: 16rpx;
border-bottom: 1rpx solid #CFD8DC;
}
 
text {
  width: 200rpx;
}
 
button {
  margin: 16rpx;
}
 
.sendMsg {
  font-size: 12;
  margin-right: 0;
  padding: 0;
  height: inherit;
  width: 80rpx;
}

  

index.js

//index.js
//獲取應用例項
const app = getApp()
 
Page({
  data: {
    send: true,
    alreadySend: false,
    second: 60,
    disabled: true,
    phoneNum: ''
  },
  // 手機號部分
  inputPhoneNum: function (e) {
    let phoneNum = e.detail.value
    this.setData({
      phoneNum: phoneNum
    })
  },
  sendMsg: function () {
    var phoneNum = this.data.phoneNum;
    if(phoneNum == ''){
      wx.showToast({
        title: '請輸入手機號碼',
        icon: 'none',
        duration: 2000
      })
      return ;
    }
    //此處省略傳送簡訊驗證碼功能
    this.setData({
      alreadySend: true,
      send: false
    })
    this.timer()
  },
  showSendMsg: function () {
    if (!this.data.alreadySend) {
      this.setData({
        send: true
      })
    }
  },
  hideSendMsg: function () {
    this.setData({
      send: false,
      disabled: true,
      buttonType: 'default'
    })
  },
  timer: function () {
    let promise = new Promise((resolve, reject) => {
      let setTimer = setInterval(
        () => {
          this.setData({
            second: this.data.second - 1
          })
          if (this.data.second <= 0) {
            this.setData({
              second: 60,
              alreadySend: false,
              send: true
            })
            resolve(setTimer)
          }
        }
        , 1000)
    })
    promise.then((setTimer) => {
      clearInterval(setTimer)
    })
  },
})

  

完整的簡訊驗證碼登入例項可參考: http://smsow.zhenzikj.com/bbs/question/detail/40.html