使用方法
class Countdown {
/**
* @param {Date} dateTo
*/
constructor(itemSelector, dateTo) {
this.itemSelector = itemSelector;
let $ = el => document.querySelector(el);
this.dateSelectors = {
d: $('.days').getContext('2d'),
h: $('.hours').getContext('2d'),
m: $('.minutes').getContext('2d'),
s: $('.seconds').getContext('2d')
};
this.dateTo = dateTo;
requestAnimationFrame(() => this.set());
}
/**
* Main function
*/
set() {
let today = new Date();
for (let selector in this.dateSelectors) {
let s = this.dateSelectors[selector];
this.clear(s);
this.setTime(s, this.dateDiff(selector, today, this.dateTo));
}
requestAnimationFrame(() => this.set());
}
/**
* Clear canvas
* @param {canvas} ctx
*/
clear(ctx) { ctx.clearRect(0, 0, 60, 60); }
setTime(ctx, until) {
ctx.font = 'bold 2rem sans-serif';
ctx.shadowColor = "#000";
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 1;
ctx.shadowBlur = 2;
ctx.fillStyle = "#ccc";
ctx.textAlign = "center";
ctx.fillText(until, 25, 40);
}
/**
*
* @param {String} datepart enum {'m', 'd', 'h', 's'}
* @param {Date} fromdate
* @param {Date} todate
*/
dateDiff(datepart, fromdate, todate) {
datepart = datepart.toLowerCase();
let diff = todate - fromdate;
let divideBy = {
d: 86400000,
h: 3600000,
m: 60000,
s: 1000,
ms: 1
};
let modulo = {
d: 1,
h: divideBy['d'],
m: divideBy['h'],
s: divideBy['m'],
ms: divideBy['s']
}
return Math.floor(diff % modulo[datepart] / divideBy[datepart]);
}
}
//set tomorrow date
new Countdown('.item-time', new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
站长提示:
1. 苦力吧素材官方QQ群:
950875342
2. 平台上所有素材资源,需注册登录会员方能正常下载。
3. 会员用户积极反馈网站、素材资源BUG或错误问题,每次奖励
2K币。
4. PHP源码类素材,如需协助安装调试,或你有二次开发需求,可联系苦力吧客服。
5. 付费素材资源,需充值后方能下载,如有任何疑问可直接联系苦力吧客服