ppt倒计时小程序_微信小程序倒计时组件实现

1、新建文件夹 count-down,选中文件夹 ->右键->选择新建Component,会自动生成 4 个文件,即

  • count-down.js
  • count-down.json
  • count-down.wxml 页面文件
  • count-down.wxss 样式文件

2、编写倒计时组件代码

count-down.wxml

<text>{{time}}</text>

count-down.js


Component({
  /**
   * 组件的属性列表
   */
  properties: {
    target: Number, // 结束时间
    callback: String, // 回调
    clearTimer: Boolean // 清除定时器
  },

  /**
   * 组件的初始数据
   */
  data: {
    time: ''
  },
  ready() {
    this.getFinalTime();
  },

  /**
   * 组件的方法列表
   */
  methods: {
    init() {
      const self = this;
      setTimeout(() => {
        self.getFinalTime.call(self);
      }, 1000);
    },
    getFinalTime() {
      const data = this.data;
      const gapTime = Math.ceil((data.target - new Date().getTime())/1000); // 距离结束时间
      let time = '00:00:00';
      if(gapTime > 0) {
        let lastTime = gapTime % 86400;
        const hour = this.formatNum(parseInt(lastTime/3600));
        lastTime = lastTime % 3600;
        const minute = this.formatNum(parseInt(lastTime/60));
        const second = this.formatNum(lastTime% 60);
        time = `${hour}:${minute}:${second}`;
        if(!data.clearTimer) this.init.call(this);
      }else {
        this.endFn();
      }
      this.setData({
        time: time
      });
    },
    formatNum(num) {
      return num > 9 ? num : `0${num}`;
    },
    endFn() {
      this.triggerEvent('callback',{});
    }
  }
})

3、使用倒计时组件

index.json:在需要用的组件的json文件中引入倒计时组件

{
  "usingComponents": {
    "count-down": "../components/count-down/count-down" 
  }
}

index.wxml:页面显示

   <view>倒计时</view>

  <count-down 
  target="{{targetTime}}"
  bindcallback="countDownCallbackFn"
  clear-timer="{{clearTimer}}"
  ></count-down>

index.js:设置倒计时的参数

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 倒计时
    targetTime: 0,
    clearTimer: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      targetTime: new Date().getTime() + 10*60000
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      clearTimer: true
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 定时器回调
   */
 countDownCallbackFn () {
    console.log("结束回调")
  }
})

ee43c21760aab55debcc594244a72ab1.png
效果展示
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值