效果如见图:
重点是在如果做到一一对应,代码如下:
wxml代码:
<view class='contents'>
<block wx:for="{{timeList}}" wx:key="">
<view class='item_list' data-id='{{index}}' bindtap='getTime' style="100%;height:100rpx;line-height:100rpx;background:#eee;margin-bottom:20rpx;">
<view>{{item.name}}:<text style="color:red;">{{insertTime[index] == null ?"":insertTime[index]}}</text></view>
</view>
</block>
</view>
js代码:
var util =require("../../utils/util.js")
Page({
/**
* 页面的初始数据
*/
data: {
timeList:[
{lastDate:"2018-07-01 10:00:00",name:"倒计时1"},
{ lastDate: "2018-04-01 10:00:00", name: "倒计时2" },
{ lastDate: "2018-08-05 10:00:00", name: "倒计时3" },
{ lastDate: "2018-09-05 10:00:00", name: "倒计时4" },
],
insertTime:[]
},
getTime: function(e){
var id = e.currentTarget.dataset.id;
var _this = this;
var timeList = _this.data.timeList;
var lastDate = timeList[id].lastDate;
lastDate = Date.parse(lastDate);
console.log(lastDate)
util.interval(lastDate,_this,id);
},
})
封装的方法:
function interval(lastTime, _this, index) {//到期时间戳
interval = setInterval(function () {
var insertTime = _this.data.insertTime;
// 获取现在的时间
var nowTime = new Date();
var nowTime = Date.parse(nowTime);//当前时间戳
var differ_time = lastTime - nowTime;//时间差:
if (differ_time >= 0) {
var differ_day = Math.floor(differ_time / (3600 * 24 * 1e3));//相差天数
var differ_hour = Math.floor(differ_time % (3600 * 1e3 * 24) / (1e3 * 60 * 60));//相差小时
var differ_minute = Math.floor(differ_time % (3600 * 1e3) / (1000 * 60));//相差分钟
var s = Math.floor(differ_time % (3600 * 1e3) % (1000 * 60) / 1000);
if (differ_day.toString().length < 2) {
differ_day = "0" + differ_day;
}
if (differ_hour.toString().length < 2) {
differ_hour = "0" + differ_hour;
}
if (differ_minute.toString().length < 2) {
differ_minute = "0" + differ_minute;
}
var str = differ_day + '天' + differ_hour + '时' + differ_minute + '分'+s;
insertTime[index] = str;
_this.setData({ insertTime: insertTime });
} else {// 当车险到期时,不再进行倒计时
console.log("不进行倒计时");
insertTime[index] = "00天00小时00分";
_this.setData({ insertTime: insertTime });
clearInterval(interval);
}
}, 1000);
}