Hexo|配置&优化倒计时挂件

1.配置


配置请参考梦爱吃鱼Penry的教程。这里不再赘述。

2.问题


countdown.js 是博客侧边栏的倒计时组件,用于展示距离下一个节日的剩余天数,以及今日/本周/本月/本年的时间进度条。

原始实现的问题: 节日目标是硬编码的:

1
2
3
4
const config = {
targetDate: "2026-01-01",
targetName: "元旦",
};

每当一个节日过去后,必须手动修改 targetDatetargetName 才能切换到下一个节日。如果忘记修改,页面会显示负数天数。

3.优化内容


将静态的单一节日配置改为自动轮转的节日列表机制,具体改动:

  1. 新增 holidays 数组 — 定义了一整年的节日列表,按月日升序排列,每个条目包含 monthdayname 三个字段。

  2. 新增 getNextHoliday() 函数 — 核心自动化逻辑:

    • 获取当天日期(时间归零到 00:00:00,避免时分秒干扰比较)
    • 遍历 holidays 列表,将每个节日映射为当年的完整日期
    • 找到第一个 大于等于今天 的节日作为目标(即:节日当天仍会显示该节日,剩余 0 天)
    • 如果今年所有节日都已过去,自动取明年第一个节日(元旦)
  3. updateCountdown() 改为动态获取目标 — 不再读取 config.targetDate,而是每次调用 getNextHoliday() 获取当前应该倒计时的节日名称和日期,动态生成日期字符串(YYYY-MM-DD 格式)和剩余天数。

  4. config 对象精简 — 移除了 targetDatetargetName,仅保留 units(进度条配置),节日数据完全由 holidays 数组管理。

代码如下,直接替换你的countdown.js

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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
const CountdownTimer = (() => {

    // 节日列表(月-日),按日期排序,每年自动循环

    const holidays = [

        { month: 1,  day: 1,  name: "元旦" },

        { month: 2,  day: 14, name: "情人节" },

        { month: 3,  day: 8,  name: "妇女节" },

        { month: 4,  day: 5,  name: "清明节" },

        { month: 5,  day: 1,  name: "劳动节" },

        { month: 5,  day: 4,  name: "青年节" },

        { month: 6,  day: 1,  name: "儿童节" },

        { month: 7,  day: 1,  name: "建党节" },

        { month: 8,  day: 1,  name: "建军节" },

        { month: 9,  day: 10, name: "教师节" },

        { month: 10, day: 1,  name: "国庆节" },

        { month: 12, day: 25, name: "圣诞节" },

    ];



    const config = {

        units: {

            day: { text: "今日", unit: "小时" },

            week: { text: "本周", unit: "天" },

            month: { text: "本月", unit: "天" },

            year: { text: "本年", unit: "天" }

        }

    };



    /**

     * 根据当前日期,找到下一个即将到来的节日

     * 如果今天正好是某个节日,则显示该节日(剩余0天)

     * 如果今年所有节日都已过,则跳到明年第一个节日

     */

    function getNextHoliday() {

        const now = new Date();

        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());



        // 先在今年找

        for (const h of holidays) {

            const date = new Date(now.getFullYear(), h.month - 1, h.day);

            if (date >= today) {

                return { name: h.name, date };

            }

        }

        // 今年的节日都过了,取明年第一个

        const first = holidays[0];

        return { name: first.name, date: new Date(now.getFullYear() + 1, first.month - 1, first.day) };

    }



    const calculators = {

        day: () => {

            const hours = new Date().getHours();

            return {

                remaining: 24 - hours,

                percentage: (hours / 24) * 100

            };

        },

        week: () => {

            const day = new Date().getDay();

            const passed = day === 0 ? 6 : day - 1;

            return {

                remaining: 6 - passed,

                percentage: ((passed + 1) / 7) * 100

            };

        },

        month: () => {

            const now = new Date();

            const total = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();

            const passed = now.getDate() - 1;

            return {

                remaining: total - passed,

                percentage: (passed / total) * 100

            };

        },

        year: () => {

            const now = new Date();

            const start = new Date(now.getFullYear(), 0, 1);

            const total = 365 + (now.getFullYear() % 4 === 0 ? 1 : 0);

            const passed = Math.floor((now - start) / 86400000);

            return {

                remaining: total - passed,

                percentage: (passed / total) * 100

            };

        }

    };



    function updateCountdown() {

        const elements = ['eventName', 'eventDate', 'daysUntil', 'countRight']

            .map(id => document.getElementById(id));



        if (elements.some(el => !el)) return;



        const [eventName, eventDate, daysUntil, countRight] = elements;

        const now = new Date();

        const { name: targetName, date: target } = getNextHoliday();

        const targetDateStr = `${target.getFullYear()}-${String(target.getMonth()+1).padStart(2,'0')}-${String(target.getDate()).padStart(2,'0')}`;



        eventName.textContent = targetName;

        eventDate.textContent = targetDateStr;

        daysUntil.textContent = Math.round((target - new Date(now.getFullYear(), now.getMonth(), now.getDate())) / 86400000);



        countRight.innerHTML = Object.entries(config.units)

            .map(([key, {text, unit}]) => {

                const {remaining, percentage} = calculators[key]();

                return `

                    <div class="cd-count-item">

                        <div class="cd-item-name">${text}</div>

                        <div class="cd-item-progress">

                            <div class="cd-progress-bar" style="width: ${percentage}%; opacity: ${percentage/100}"></div>

                            <span class="cd-percentage ${percentage >= 46 ? 'cd-many' : ''}">${percentage.toFixed(2)}%</span>

                            <span class="cd-remaining ${percentage >= 60 ? 'cd-many' : ''}">

                                <span class="cd-tip">还剩</span>${remaining}<span class="cd-tip">${unit}</span>

                            </span>

                        </div>

                    </div>

                `;

            }).join('');

    }



    function injectStyles() {

        const styles = `

            .card-countdown .item-content {

                display: flex;

            }

            .cd-count-left {

                position: relative;

                display: flex;

                flex-direction: column;

                margin-right: 0.8rem;

                line-height: 1.5;

                align-items: center;

                justify-content: center;

            }

            .cd-count-left .cd-text {

                font-size: 14px;

            }

            .cd-count-left .cd-name {

                font-weight: bold;

                font-size: 18px;

            }

            .cd-count-left .cd-time {

                font-size: 30px;

                font-weight: bold;

                color: var(--anzhiyu-main);

            }

            .cd-count-left .cd-date {

                font-size: 12px;

                opacity: 0.6;

            }

            .cd-count-left::after {

                content: "";

                position: absolute;

                right: -0.8rem;

                width: 2px;

                height: 80%;

                background-color: var(--anzhiyu-main);

                opacity: 0.5;

            }

            .cd-count-right {

                flex: 1;

                margin-left: .8rem;

                display: flex;

                flex-direction: column;

                justify-content: space-between;

            }

            .cd-count-item {

                display: flex;

                flex-direction: row;

                align-items: center;

                height: 24px;

            }

            .cd-item-name {

                font-size: 14px;

                margin-right: 0.8rem;

                white-space: nowrap;

            }

            .cd-item-progress {

                position: relative;

                display: flex;

                flex-direction: row;

                align-items: center;

                justify-content: space-between;

                height: 100%;

                width: 100%;

                border-radius: 8px;

                background-color: var(--anzhiyu-background);

                overflow: hidden;

            }

            .cd-progress-bar {

                height: 100%;

                border-radius: 8px;

                background-color: var(--anzhiyu-main);

            }

            .cd-percentage,

            .cd-remaining {

                position: absolute;

                font-size: 12px;

                margin: 0 6px;

                transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out;

            }

            .cd-many {

                color: #fff;

            }

            .cd-remaining {

                opacity: 0;

                transform: translateX(10px);

            }

            .card-countdown .item-content:hover .cd-remaining {

                transform: translateX(0);

                opacity: 1;

            }

            .card-countdown .item-content:hover .cd-percentage {

                transform: translateX(-10px);

                opacity: 0;

            }

        `;



        const styleSheet = document.createElement("style");

        styleSheet.textContent = styles;

        document.head.appendChild(styleSheet);

    }



    let timer;

    const start = () => {

        injectStyles();

        updateCountdown();

        timer = setInterval(updateCountdown, 600000);

    };



    ['pjax:complete', 'DOMContentLoaded'].forEach(event => document.addEventListener(event, start));

    document.addEventListener('pjax:send', () => timer && clearInterval(timer));



    return { start, stop: () => timer && clearInterval(timer) };

})();

效果

  • 部署后无需再手动维护,节日会自动按时间顺序轮转
  • 如需增减节日,只需修改 holidays 数组即可,格式为 { month: 月, day: 日, name: "名称" }进行