count-down.js
2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* countDown.js.
* @author hgwang
* @date 2016-07-27
*/
'use strict';
import Vue from 'vue';
Vue.directive('countDown', {
bind: function(el, binding) {
// 结束时间
let value = binding.value.endTime || 0;
let callbackFn = binding.value.callback;
// 如果不为0的话根据剩余的秒数计算时间
let leftTime = parseInt(binding.value.leftTime, 10);
let newValue;
if (leftTime !== 0) {
newValue = new Date() - 0 + leftTime * 1000;
} else {
if (value) {
newValue = value.replace(/-/g, '/').substring(0, 19);
} else {
return '';
}
}
if (new Date(newValue) === 'Invalid Date') {
return console.error('The param of directive "v-time-down" must be a date string!');
}
let timerSS = null;
let hDom = document.createElement('span');
hDom.setAttribute('class', 'timeDown-H');
el.appendChild(hDom);
let last = 0;
function format(val) {
let result = '00:00:00';
if (val === 0) {
return result;
}
let h = parseInt(val / 3600, 10);
let m = parseInt((val - h * 3600) / 60, 10);
let s = parseInt(val - h * 3600 - m * 60, 10);
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
s = s < 10 ? '0' + s : s;
if (h === 0) {
result = m + ':' + s;
} else {
result = h + ':' + m + ':' + s;
}
return result;
}
function countdown() {
last = (new Date(newValue)).getTime() - (new Date()).getTime();
last = last / 1000;
if (last <= 0) {
clearInterval(timerSS);
last = 0;
callbackFn && callbackFn();
}
el.querySelector('.timeDown-H').innerHTML = format(last);
}
countdown();
timerSS = setInterval(countdown, 1000);
}
});