前言

在页脚放一个运行时间,每秒更新一次。建站日期改成自己的就行,页面切换后也能继续显示。

美化之前

本站使用 Hexo 6.0.0 + Butterfly 4.5.1,其他版本请按实际情况调整。样式、脚本引入及全局变量用法可参考:

参考链接

  • Leonus《博客底部运行时间》:https://blog.leonus.cn/2022/footer.html(原链接暂不可用)。

修改方案

1. 添加页脚容器

在 themes/butterfly/layout/includes/footer.pug 中找到希望显示运行时间的位置,加入:

1
#runtime

本站把它放在 #footer-right 下。ID 一页只放一个,不要在版权文字里再建一份同名容器。

2. 添加脚本

新建 source/static/js/interval.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(() => {
if (window.__juneRuntimeTimer) clearInterval(window.__juneRuntimeTimer);
const created = new Date('2023-12-02T00:00:00+08:00').getTime();
const update = () => {
const target = document.getElementById('runtime');
if (!target) return;
let seconds = Math.max(0, Math.floor((Date.now() - created) / 1000));
const days = Math.floor(seconds / 86400);
seconds %= 86400;
const hours = Math.floor(seconds / 3600);
seconds %= 3600;
const minutes = Math.floor(seconds / 60);
const rest = seconds % 60;
const pad = n => String(n).padStart(2, '0');
target.textContent = `本站已运行:${days} 天 ${pad(hours)} 时 ${pad(minutes)} 分 ${pad(rest)} 秒`;
};
window.__juneRuntimeTimer = setInterval(update, 1000);
if (!window.__juneRuntimePjaxBound) {
document.addEventListener('pjax:complete', update);
window.__juneRuntimePjaxBound = true;
}
update();
})();

然后在 _config.butterfly.yml 的 inject.bottom 里引入。

1
2
3
inject:
bottom:
- <script defer src="/static/js/interval.js"></script>

如果和我一样用了 JS 自动注入,就在 source/static/js/_inject.yml 的 bottom 里添加文件名,不要重复引入。这里绑定了全局事件的脚本设为 pjax: false,避免切换页面时重复绑定。

3. 时间设置

本站原脚本使用 2023/12/02 00:00:00,并按固定 365 天折算“年”。这版代码使用带 +08:00 的 ISO 时间,统一按总天数显示,不把固定 365 天解释成准确的自然年。

每次更新都重新查询容器,避免页脚替换后还在更新脱离页面的旧节点;全局定时器登记后也可避免重复执行产生多个计时器。首次就刷新,不必等第一秒才有文字。

如果你的建站时间不同,修改 created 那一行。时钟依赖访客设备时间,设备时间不准时显示也会偏差,它不是服务器运行时长监控。