前言
该教程基于 butterfly 的主题进行配置
因为自己也想弄一个这种东西,结果一搜发现全都是 next 主题的
于是打算根据
https://blog.hikariyo.net/js/hexo-realtime-duration-footer/index.html
大佬的教程重新编写整理一个教程,因为我根据他的方法并没有成功弄好))
配置文件修改
本文用 Dayjs
来处理日期。当然,完全可以用原生
Date
,但是 js
代码的编写在时间处理上会多出很多需要注意的细节
我使用的是 butterfly
主题。如果读者正在使用别的主题,请查阅对应官方文档寻找如何插入自定义标签与自定义页脚信息。
在主题配置文件(即_config.butterfly.yml
)中引入:
1 2 3 4 5
| inject: bottom: - <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.7/dayjs.min.js"></script> - <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.7/plugin/duration.min.js"></script> - <script src="/scripts/realtime.js"></script>
|
注意是 bottom
部分
在自定义页脚中加入一个 span
元素提供显示日期的位置
1 2 3
| footer: custom_text: - '<span id="realtime_duration"></span>'
|
接下来主要通过 setInterval
实现这样一个实时更新的功能。
实现功能
在 source
目录下创建
scripts/realtime.js
,写入以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13
| (() => { dayjs.extend(window.dayjs_plugin_duration) const el = document.getElementById('realtime_duration') const date = dayjs('2022-05-19')
setInterval(() => { const dur = dayjs.duration(dayjs().diff(date)) const days = String(Math.floor(dur.asDays())) el.innerHTML = '已运行' + days + dur.format('天HH时mm分ss秒') }, 1000) })()
|
注意是 文件路径为
your_hexo_blog/source/scripts/realtime.js
如果 source
下没有
scripts
,直接新建一个就行
不成功的额外修改
如果到这里你顺利显示了,就是正常的情况了,接下来都是我自己摸索的额外的不成功的话该如何配置
如果没有成功加载,先去看看你的 public 中存放 js
的文件夹看看有没有成功加载 realtime.js
这里会有一个问题,切换页面,日期显示就会消失???
其实就是 Pjax 兼容的问题,你开了 Pjax就会这样,这个官方文档里也说了
Pjax 会导致部分 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
| document.addEventListener('DOMContentLoaded', initRuntime) document.addEventListener('pjax:complete', initRuntime)
function initRuntime() { dayjs.extend(window.dayjs_plugin_duration) const el = document.getElementById('realtime_duration') if (!el) return
const startDate = dayjs('2022-05-19T00:00:00+08:00') const updateTime = () => { const now = dayjs() const duration = dayjs.duration(now.diff(startDate)) const days = duration.days() const hours = duration.hours().toString().padStart(2, '0') const minutes = duration.minutes().toString().padStart(2, '0') const seconds = duration.seconds().toString().padStart(2, '0')
el.innerHTML = `网站正常或不正常的运行了${days}天${hours}时${minutes}分${seconds}秒` }
updateTime() setInterval(updateTime, 1000) }
|
这个 CSS 样式根据需要添加
1 2 3 4 5 6 7 8 9 10 11 12
| #footer-wrap .footer-separator { display: none; }
#realtime_duration { font-size: 0.9em; color: #666; letter-spacing: 0.5px; white-space: nowrap; }
|