【微信小程式】原生小程式,實現簡單的倒計時外掛
阿新 • • 發佈:2020-08-18
建立外掛
外掛程式碼
- count-down.wxml
<view class="count-down"> <text class="days" wx:if="{{showDays}}">{{days}}</text> <text class="spot" wx:if="{{showDays}}">{{spot.days}}</text> <text class="hours" wx:if="{{showHours}}">{{hours}}</text> <text class="spot" wx:if="{{showHours}}">{{spot.hours}}</text> <text class="minutes" wx:if="{{showMinute}}">{{minutes}}</text> <text class="spot" wx:if="{{showMinute}}">{{spot.minutes}}</text> <text class="seconds">{{seconds}}</text> <text class="spot">{{spot.seconds}}</text> </view>
> 顯示的格式:xx天xx時xx分xx秒,或者 00:00:00:00,更多格式根據需求配置
> 根據需求配置精確度:天、時、分、秒
- count-down.js
Component({ data: { timers: false, // 定時器 days: '00', // 天 hours: '00', // 時 minutes: '00', // 分 seconds: '00', // 秒 spotList: { // 倒計時格式,按需配置 1: { 'days': ':', 'hours': ':', 'minutes': ':', 'seconds': '', }, 2: { 'days': '天', 'hours': '時', 'minutes': '分', 'seconds': '秒' } }, }, properties: { eTime: { type: Number, value: 0 }, spotType: { type: Number, value: 1 }, showMinute: { type: Number, value: 1 }, showHours: { type: Number, value: 1 }, showDays: { type: Number, value: 1 }, }, observers: { }, lifetimes: { attached() { this.clockInit(); }, datached() { clearInterval(this.data.timers); } }, methods: { // 初始化 clockInit() { var spotList = this.data.spotList, spotType = this.data.spotType; this.setData({ spot: spotList[spotType], showDays: this.data.showDays, showHours: this.data.showHours, showMinute: this.data.showMinute }); var secondTime = this.data.eTime; this.data.timers = setInterval(() => { if (secondTime <= 0) { return this.endOfTime() } secondTime--; this.countDown(secondTime); }, 1000); }, // 倒計時結束 endOfTime() { clearInterval(this.data.timers); this.triggerEvent('endOfTime', 1); }, // 計算時分秒 countDown(secondTime) { var seconds = secondTime, minutes = 0, hours = 0, days = 0; if (this.data.showMinute) { minutes = Math.floor(seconds / 60); seconds = seconds % 60; } if (this.data.showHours) { hours = Math.floor(minutes / 60); minutes = minutes % 60; } if (this.data.showDays) { days = Math.floor(hours / 24); hours = hours % 24; } this.setData({ days: this.zeroFill(days), hours: this.zeroFill(hours), minutes: this.zeroFill(minutes), seconds: this.zeroFill(seconds) }); }, // 補零 zeroFill(n, type) { if(type == 's') { return parseInt(n) < 10 && parseInt(n) >= 0 ? "0" + parseInt(n) : parseInt(n) }else { return parseInt(n) < 10 && parseInt(n) >= 0 ? "0" + n : n } } } })
外掛使用
- wxml:初始化倒計時秒數、顯示格式、倒計時結束觸發事件
<count-down eTime="{{order.count_down}}" bind:endOfTime="endOfTime" showDays="false" showHours="false" wx:if="{{order.count_down > 0}}"/>
- js
endOfTime: function (e) { console.log('endOf }