微信小程序订单倒计时功能实现源码
发布于 5 年前 作者 fuxia 3740 次浏览 来自 分享

效果:

功能没有特别说明的,也不难,只是繁琐一点,直接给大家上代码了,哪些代码对大家有用直接粘过去就行。

wxml:

<view class="countdownBox">
   <text>结束倒计时:</text>
   <view class="item">{{countdown.day}}</view>
   <text>天</text>
   <view class="item">{{countdown.hour}}</view>
   <text>时</text>
   <view class="item">{{countdown.minute}}</view>
   <text>分</text>
   <view class="item">{{countdown.second}}</view>
   <text>秒</text>
</view>

wxss:

.countdownBox {
  width: 100%;
  height: 80rpx;
  background-color: red;
  border-radius: 50rpx;
  margin-top: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 30rpx;
  margin-bottom: 20rpx;
}
.countdownBox .item{
  height: 60rpx;
  background-color: #fff;
  color: #000;
  box-sizing: border-box;
  padding: 0rpx 8rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 35rpx;
  font-weight: 480;
  margin: 0rpx 10rpx;
}

js:

Page({
  data: {
    countdown:{
      day: '',
      hour: '',
      minute: '',
      second: ''
    }
  },
//开始
  startCountdown: function (serverTime, endTime) {
    var that = this;
    serverTime = new Date(serverTime);
    var millisecond = endTime.getTime() - serverTime.getTime();
     
    var interval = setInterval(function () {
      console.log('循环中');
      millisecond -= 1000;
      if (millisecond <= 0){
        clearInterval(interval);
        that.setData({
          countdown: {
            day: '00',
            hour: '00',
            minute: '00',
            second: '00'
          }
        });
        return;
      }
      that.transformRemainTime(millisecond);
    }, 1000);
  },
  // 剩余时间(毫秒)处理转换时间
  transformRemainTime: function (millisecond) {
    var that = this;
    var countdownObj = that.data.countdown;
    // 秒数
    var seconds = Math.floor(millisecond / 1000);
    // 天数
    countdownObj.day = that.formatTime(Math.floor(seconds / 3600 / 24));
    // 小时
    countdownObj.hour = that.formatTime(Math.floor(seconds / 3600 % 24));
    // 分钟
    countdownObj.minute = that.formatTime(Math.floor(seconds / 60 % 60));
    // 秒
    countdownObj.second = that.formatTime(Math.floor(seconds % 60));
    that.setData({
      countdown: countdownObj
    });
  },
  //格式化时间为2位
  formatTime: function(time){
    if(time < 10)
      return '0' + time;
    return time;
  },

我这里的serverTime是获得的小程序云服务器时间, endTime是倒计时结束时间,将二者间的差转为天、时、分、秒就行了。

完整代码下载: http://market.zhenzikj.com/detail/97.html

回到顶部