57 lines
2.3 KiB
JavaScript
57 lines
2.3 KiB
JavaScript
function initClassTimers() {
|
||
const timers = document.querySelectorAll('.js-event-timer');
|
||
|
||
timers.forEach(timer => {
|
||
const targetTimeStr = timer.getAttribute('data-target');
|
||
const labelEl = timer.querySelector('.js-timer-label');
|
||
const daysEl = timer.querySelector('.js-days');
|
||
const hoursEl = timer.querySelector('.js-hours');
|
||
const minutesEl = timer.querySelector('.js-minutes');
|
||
const secondsEl = timer.querySelector('.js-seconds');
|
||
|
||
// 清除可能存在的旧定时器(防止PJAX导致的叠加)
|
||
if (timer.timerId) clearInterval(timer.timerId);
|
||
|
||
function updateTimer() {
|
||
const targetDate = new Date(targetTimeStr).getTime();
|
||
// 简单格式校验,防止 Excerpt 填错导致报错
|
||
if (isNaN(targetDate)) {
|
||
if (labelEl) labelEl.innerText = "日期错误";
|
||
return;
|
||
}
|
||
|
||
const now = new Date().getTime();
|
||
const difference = targetDate - now;
|
||
const isPast = difference < 0;
|
||
const absDiff = Math.abs(difference);
|
||
|
||
// 更新状态标签
|
||
if (labelEl) {
|
||
labelEl.innerText = isPast ? "已经过去" : "倒计时中";
|
||
}
|
||
|
||
// 计算时间
|
||
const d = Math.floor(absDiff / (1000 * 60 * 60 * 24));
|
||
const h = Math.floor((absDiff / (1000 * 60 * 60)) % 24);
|
||
const m = Math.floor((absDiff / 1000 / 60) % 60);
|
||
const s = Math.floor((absDiff / 1000) % 60);
|
||
|
||
// 更新数字显示 (加了动画平滑过渡感)
|
||
if (daysEl) daysEl.innerText = d.toString().padStart(2, '0');
|
||
if (hoursEl) hoursEl.innerText = h.toString().padStart(2, '0');
|
||
if (minutesEl) minutesEl.innerText = m.toString().padStart(2, '0');
|
||
if (secondsEl) secondsEl.innerText = s.toString().padStart(2, '0');
|
||
}
|
||
|
||
updateTimer();
|
||
timer.timerId = setInterval(updateTimer, 1000);
|
||
});
|
||
}
|
||
|
||
// 首次加载执行
|
||
document.addEventListener('DOMContentLoaded', initClassTimers);
|
||
|
||
// PJAX 兼容执行 (适配 Ghost 常用的主题加载方式)
|
||
if (typeof pjax !== 'undefined' || document.querySelector('[data-pjax]')) {
|
||
document.addEventListener('pjax:complete', initClassTimers);
|
||
} |