效果:
功能沒有特別說明的,也不難,只是繁瑣一點,直接給大家上代碼了,哪些代碼對大家有用直接粘過去就行。
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是倒計時結束時間,將二者間的差轉為天、時、分、秒就行了。
完整代碼下載: 活動報名小程序 微信小程序-榛子應用市場