其實,原理很簡單。
知道結束時間之后,進行計算,還有多少天,多少小時,多少分,多少秒。
每秒刷新一次時間。
倒計時結束之后,不再刷新,統統清零。
data: {
endTime: '', // 時間戳
},
// 倒計時
countDown: function () {
var that = this;
var nowTime = new Date().getTime();//現在時間(時間戳)
// var endTime = new Date(that.data.endTime).getTime();//結束時間(時間戳)
var endTime = that.data.endTime * 1000;//結束時間(時間戳)
var time = (endTime - nowTime) / 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);
// console.log(day + "," + hou + "," + min + "," + sec)
day = that.timeFormin(day),
hou = that.timeFormin(hou),
min = that.timeFormin(min),
sec = that.timeFormin(sec);
// 天,換成小時
hou = day * 24 + hou;
that.setData({
// day: that.timeFormat(day),
hou: that.timeFormat(hou),
min: that.timeFormat(min),
sec: that.timeFormat(sec)
})
// 每1000ms刷新一次
if (time > 0) {
that.setData({
countDown: true
})
setTimeout(this.countDown, 1000);
} else {
that.setData({
countDown: false
})
}
},
//小於10的格式化函數(2變成02)
timeFormat(param) {
return param < 10 ? '0' + param : param;
},
//小於0的格式化函數(不會出現負數)
timeFormin(param) {
return param < 0 ? 0 : param;
}
onLoad: function ({ id }) {
this.openid = app.globalData.openid || Storage.get().openid;
request("getSeckillDetail", { id, openid: this.openid }).then(({ data }) => {
this.setData({
bannerList: data.product_banner_list,
productInfo: data.product_info,
productDetail: data.product_sample_list,
endTime: data.end_time
});
// 開啟倒計時
var that = this;
that.countDown()
});
}
后台,返回時間戳,或者結束時間字符串都可以。前台,根據不同結果,進行處理。
處理成,day,hou,min,sec在頁面中展示。
html
<view class="seckill_box">
<view class="left">
<view class="title">秒殺搶購中</view>
<progress class="process" percent="20" backgroundColor="#9F2033" activeColor="#FFE0E5" font-size="20rpx" border-radius="5rpx" stroke-width="10rpx" show-info />
</view>
<view class="right">
<view class="title">距本場結束剩余</view>
<view class="count_down">
<text class="time">{{hou}}</text> : <text class="time">{{min}}</text> : <text class="time">{{sec}}</text>
</view>
</view>
</view>
css
.seckill_box {
width:750rpx;
height: 100rpx;
background-color: #E9455E;
display: flex;
.left {
padding-top: 18rpx;
width: 50%;
height: 100rpx;
padding-left: 40rpx;
.title {
font-size: 32rpx;
font-weight: bold;
color:#fff;
}
.process {
width: 90%;
color:#FFF;
}
}
.right {
width: 50%;
height: 100rpx;
padding-left:172rpx;
padding-top: 18rpx;
.title {
font-size: 24rpx;
font-weight: 500;
color:#FFF;
}
.count_down {
margin-top:5rpx;
margin-left:15rpx;
font-size: 20rpx;
font-weight: 500;
color:#FFF;
.time {
color:#E9455E;
padding-left:5rpx;
padding-right:5rpx;
min-width: 36rpx;
height: 26rpx;
text-align: center;
line-height: 26rpx;
background-color: #FFF;
display: inline-block;
}
}
}
}