做小程序项目中,需要做一个倒计时功能,如下图:
记录一下实现步骤:
1.考虑到这个功能可能会有多处用到,所以把倒计时的函数写在utils.js里面:
const formatNumber = n => { n = n.toString() return n[1] ? n : '0' + n } // 倒计时 function countDown(that) { //倒计时函数 let newTime = new Date().getTime(); let endTime = that.data.endTime; let remainTime = endTime - newTime; let obj = null; let t = ''; // 如果活动未结束,对时间进行处理 if (remainTime > 0) { let time = remainTime / 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: formatNumber(day), hou: formatNumber(hou), min: formatNumber(min), sec: formatNumber(sec) } } t = setTimeout(function() { that.setData({ countDownTxt: obj }); countDown(that) }, 1000) if (remainTime <= 0) { clearTimeout(t); } }
module.exports = {
countDown: countDown,
}
2.在目标页面的js里面引用该js,并执行倒计时方法:
//获取应用实例 var app = getApp(); var ss = require('../../../utils/utils.js') Page({ /** * 页面的初始数据 */ data: { nowTime: new Date().getTime(), //获取当前日期 endTime: 1533177202000,//结束日期时间戳 remainTime: null, countDownTxt:null, }, onLoad: function(options) { this.setData({ remainTime: this.data.endTime - this.data.nowTime }) }, onShow: function() { ss.countDown(this); }, })
wxml:
<view class="course-countdown"> <block wx:if="{{remainTime>0}}"> <text class='block fs-28'>距活动结束:</text> <view class="countdown-result fs-24 mt-5"> <text>{{countDownTxt.day}}</text> 天 <text>{{countDownTxt.hou}}</text> 时 <text>{{countDownTxt.min}}</text> 分 <text>{{countDownTxt.sec}}</text> 秒 </view> </block> <block wx:else> <text class="fs-28">该活动已结束</text> </block> </view>
O啦~~~