前言

在使用 Hexo 配合 Butterfly 主题,并安装 hexo-bilibili-bangumi 插件生成 bangumis 页面时,我遇到了一个问题:

我在页面 front-matter 中设置了 top_img,但是本地预览时,bangumis 页面顶部封面依然显示默认图片,无法生效。

下面分享整个排查和解决过程,希望对同样遇到问题的人有帮助。

问题分析

  1. 插件生成页面覆盖 front-matter
    hexo-bilibili-bangumi 插件在生成 bangumis 页面时,会使用自己的模板生成页面,进而导致文章 front-matter 的 top_img失效。
  2. Butterfly 主题渲染机制
    主题在渲染页面顶部封面时,会读取 header#page-headerstyle="background-image: ...",而不是 <img> 标签,所以直接使用 .top-img JS 替换 <img> 无效。

解决方案:使用JS动态替换

由于 bangumis 页面顶部是 CSS 背景图,可以用 JS 动态替换:

  1. themes/butterfly/source/js/ 下新建 custom.js(如果没有)。
  2. 写入以下代码:
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
/**
* custom.js
* 用于 Hexo + Butterfly 主题统一替换 Bangumis 和 Cinema 页面顶部封面
* 背景图直接替换 header#page-header 的 background-image
*/

document.addEventListener('DOMContentLoaded', function() {
// 页面路径判断
const path = location.pathname;

// Bangumis 页面
if (path.includes('/bangumis')) {
const header = document.querySelector('#page-header');
if (header) {
header.style.backgroundImage = 'url(图片链接)';
}
}

// Cinema 页面
if (path.includes('/cinemas')) {
const header = document.querySelector('#page-header');
if (header) {
header.style.backgroundImage = 'url(图片链接)';
}
}

// 其他页面可按需扩展
});

  1. _config.butterfly.yml 中引入:
1
2
3
4
5
6
inject:
head:
# - <link rel="stylesheet" href="/xxx.css">
bottom:
# - <script src="xxxx"></script>
- <script src="/js/custom.js"></script>
  1. 执行:
1
2
3
hexo clean
hexo ge
hexo s

刷新浏览器,就会看到自定义的封面图生效。