最近做小程序商城。列表秒殺倒計時這個坑死了。還是借鑒網上大佬的方法
let goodsList = [{ actEndTime: '2018-06-24 10:00:43' }] let endTimeList = []; // 將活動的結束時間參數提成一個單獨的數組,方便操作 this.data.mydata.rush.forEach(o => { endTimeList.push(o.actEndTime) }) this.setData({ actEndTimeList: endTimeList }); // 執行倒計時函數 this.countDown(); timeFormat(param) { //小於10的格式化函數 return param < 10 ? '0' + param : param; }, countDown(it) { //倒計時函數 // 獲取當前時間,同時得到活動結束時間數組 let newTime = new Date().getTime(); let endTimeList = this.data.actEndTimeList; let countDownArr = []; // 對結束時間進行處理渲染到頁面 endTimeList.forEach(o => { let endTime = new Date(o).getTime(); let obj = null; // 如果活動未結束,對時間進行處理 if (endTime - newTime > 0) { let time = (endTime - newTime) / 1000; // 獲取天、時、分、秒 let day = parseInt(time / (60 * 60 * 24)); let hou = parseInt(time % (60 * 60 * 24) / 3600); let min = parseInt(time % (60 * 60 * 24) % 3600 / 60); let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60); obj = { day: this.timeFormat(day), hou: this.timeFormat(hou), min: this.timeFormat(min), sec: this.timeFormat(sec) } } else { //活動已結束,全部設置為'00' obj = { day: '00', hou: '00', min: '00', sec: '00' } } countDownArr.push(obj); }) // 渲染,然后每隔一秒執行一次倒計時函數 this.setData({ countDownList: countDownArr }) setTimeout(this.countDown, 1000); },
<view class='item-money-name'> <view class='item-money'>¥{{item.money}}</view> <view class="tui-countdown-content {{(countDownList[index].day && countDownList[index].hou && countDownList[index].min && countDownList[index].sec) == 0?'tibg':''}}"> <text>剩余</text> <text class='tui-conutdown-box'>{{countDownList[index].day}}</text> <text>天</text> <text class='tui-conutdown-box'>{{countDownList[index].hou}}:</text> <text class='tui-conutdown-box'>{{countDownList[index].min}}:</text> <text class='tui-conutdown-box'>{{countDownList[index].sec}}</text> </view> </view>
countDownList: []
主要是將獲取到的時間循環出來單獨存一個數組。然后再倒計時。獲取的時間和計算機的時間對比。
然后再每個商品的index下便可獲取到每個倒計時了