效果如图:
代码:
1 Ext.define('ux.label.Countdown', { 2 alternateClassName: 'labelCountdown', 3 extend: 'Ext.Component', 4 xtype: 'labelCountdown', 5 config: { 6 baseCls: Ext.baseCSSPrefix + 'label', 7 format: 'Y-m-d H:i:s', 8 value: null 9 }, 10 initialize: function () { 11 this.callParent(); 12 this.on({ 13 hide: 'stop', 14 scope: this 15 }); 16 }, 17 stop: function () { 18 console.log('停止计时'); 19 clearInterval(this.task); 20 this.isStart = false; 21 }, 22 start: function () { 23 var me = this; 24 if (!me.isStart && me.time) { 25 console.log('开始计时'); 26 me.isStart = true; 27 me.task = setInterval(function () { 28 me.timing(me); 29 },1000); 30 me.timing(me); 31 } 32 }, 33 updateValue: function (time,old) { 34 //console.log(time); 35 var me = this; 36 if (time) { 37 time = Ext.Date.parse(time, me.getFormat()); 38 if (time) { 39 me.time = time; 40 me.start(); 41 } 42 } 43 }, 44 timing: function (me) { 45 if (!me.time) { 46 clearInterval(me.task); 47 console.log('停止计时'); 48 } else { 49 var now = new Date(), 50 ms = me.time - now, 51 //计算出开始时间和现在时间的时间戳差 52 day = Math.floor(ms / (1000 * 60 * 60 * 24)), 53 //天数 54 hour = Math.floor(ms / (1000 * 60 * 60)) % 24, 55 //小时 56 minute = Math.floor(ms / (1000 * 60)) % 60, 57 //分钟 58 second = Math.floor(ms / 1000) % 60, 59 //秒 60 label; 61 if (ms > 0) { 62 console.log('正在计时'); 63 if (day > 0) { 64 label = util.format('剩余{0}天{1}小时{2}分{3}秒', day, hour, minute, second); 65 } else if (hour > 0) { 66 label = util.format('剩余{0}小时{1}分{2}秒', hour, minute, second); 67 } else if (minute > 0) { 68 label = util.format('剩余{0}分{1}秒', minute, second); 69 } else if (second >= 0) { 70 label = util.format('剩余{0}秒', second); 71 } 72 me.setHtml(label); 73 } else { 74 console.log('计时结束'); 75 me.setHtml('已结束'); 76 me.fireEvent('end', me); 77 clearInterval(me.task); 78 } 79 } 80 } 81 });
使用:
xtype: 'labelCountdown', //format默认格式 format: 'Y-m-d H:i:s', //这里需要和上面的format对应,否则无法转换成时间,其他参数和lable相同 value: '2014-01-01 23:21:45'
注意根据情况调用start和stop方法,以免陷入无限循环