介绍
本文将会详细介绍一图流背景与顶部图的修改过程。

设置图片

这个是 Butterfly 自带的功能,修改主题的配置文件 _config.butterfly.yml

编辑 index_imgbackgroundfooter_bg 选项。
设置网站背景,并将主页顶部图和页脚背景改为透明。
(需要将以下示例地址替换为自己的图片地址。)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Image (圖片設置)
# --------------------------------------

# The banner image of home page
index_img: transparent

# Beautify/Effect (美化/效果)
# --------------------------------------

# Website Background (設置網站背景)
# can set it to color or image (可設置圖片 或者 顔色)
# The formal of image: url(http://xxxxxx.com/xxx.jpg)
background: url(https://example.com/img/background.jpg)

# Footer Background
footer_bg: transparent

引入相关样式

新建一个文件,位于 source/css/modify.styl,并增加以下内容。
(此处只是举例,也可以使用自己已有的样式文件。)

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
@import 'nib'

// 顶部图
#page-header
&, &:before
background: transparent !important
&.post-bg, &.not-home-page
height: 280px !important
#post-info
bottom: 40px !important
#page-site-info
top: 140px !important

@media screen and (max-width: 768px)
&.not-home-page
height: 200px !important
#post-info
bottom: 10px !important
#page-site-info
top: 100px !important

.top-img
height: 250px
margin: -50px -40px 50px
border-top-left-radius: inherit
border-top-right-radius: inherit
background-position: center center
background-size: cover
transition: all 0.3s

@media screen and (max-width: 768px)
height: 230px
margin: -36px -14px 36px

[data-theme='dark'] &
filter: brightness(0.8)

// 页脚
#footer:before
background-color: alpha(#FFF, .5)

[data-theme='dark'] &
background-color: alpha(#000, .5)

#footer-wrap, #footer-wrap a
color: #111
transition: unset

[data-theme='dark'] &
color: var(--light-grey)

在主题配置文件 _config.butterfly.ymlinject.head 引入样式。

1
2
3
4
5
6
7
8
9
# other (其他)
# --------------------------------------

# Inject
# Insert the code to head (before '</head>' tag) and the bottom (before '</body>' tag)
# 插入代码到头部 </head> 之前 和 底部 </body> 之前
inject:
head:
- <link rel="stylesheet" href="/css/modify.css">

modify.styl 会被 Hexo 渲染成 modify.css 文件,所以此处应为 modify.css

增加插件脚本

因为使用了 cheerio 来解析 HTML,所以需要先安装此依赖。

1
npm install cheerio

新建一个文件,位于 scripts/modify.js,并增加以下内容。
(此处只是举例,也可以使用自己已有的插件脚本文件。)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
'use strict';
const cheerio = require('cheerio');

/**
* 在页面插入新顶部图
* @param {cheerio.Root} $ Root
*/
function insertTopImg($) {
let header = $('#page-header');
if (header.length === 0) return;
let background = header.css('background-image');
if (!background) return;
$('#post, #page, #archive, #tag, #category').prepend(`<div class="top-img" style="background-image: ${background};"></div>`);
}

hexo.extend.filter.register('after_render:html', function(str, data) {
let $ = cheerio.load(str, {
decodeEntities: false
});
insertTopImg($);
return $.html();
});

验证效果

使用hexo 三连查看效果。

1
2
3
hexo cl
hexo g
hexo s

参考链接:https://android99.com/2021/08/10/butterfly-top-image-modify/