小程序(實現多個倒計時interval)


效果如見圖:

 

重點是在如果做到一一對應,代碼如下:

wxml代碼:

<view class='contents'>
  <block wx:for="{{timeList}}" wx:key="">
    <view class='item_list' data-id='{{index}}' bindtap='getTime' style="width: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);

}
 
 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM