配置butterfly主题时,如果想设置随机封面,会发生这么一种情况,就是有些文章封面图片都是同一张,如下所示:
noRandomCover

解决方案

博客更目录/themes/butterfly/scripts

新建random_img.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
/**
* Butterfly
* ramdom cover
*/

'use strict'

hexo.extend.filter.register('before_post_render', function (data) {
const { config } = this
if (config.post_asset_folder) {
const imgTestReg = /\.(png|jpe?g|gif|svg|webp)(\?.*)?$/
const topImg = data.top_img
const cover = data.cover
if (topImg && topImg.indexOf('/') === -1 && imgTestReg.test(topImg)) data.top_img = data.path + topImg
if (cover && cover.indexOf('/') === -1) data.cover = data.path + cover
}

if (data.cover === false) {
data.randomcover = randomCover()
return data
}

data.cover = data.cover || randomCover()
return data
}, 0)

function randomCover() {
const theme = hexo.theme.config
let cover
let num

if (theme.cover && theme.cover.default_cover) {
if (!Array.isArray(theme.cover.default_cover)) {
cover = theme.cover.default_cover
} else {
num = Math.floor(Math.random() * theme.cover.default_cover.length)
cover = theme.cover.default_cover[num]
}
} else {
cover = theme.default_top_img || 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
}
if (theme.cover.suffix) {
if (theme.cover.suffix == 1)
cover = cover + ("?" + Math.ceil(Math.random() * 10000))
else if (theme.cover.suffix == 2)
cover = cover + ("&" + Math.ceil(Math.random() * 10000))
}
return cover
}

更改主题配置文件

cover:增加suffix:
选项如下:

  1. 0 不使用后缀
  2. 1 ?加随机数
  3. 2 &加随机数

完成🎉