前言

最近想再给文章添加封面,但是每一个文章都需要找封面着实麻烦,有没有一种随机的,默认的就可以添加的呢。以下是一种解决方法。

解决过程

在butterfly主题中有这样的配置

1
2
3
4
5
6
7
8
9
10
11
12
cover:
# display the cover or not (是否顯示文章封面)
index_enable: true
aside_enable: true
archives_enable: true
# the position of cover in home page (封面顯示的位置)
# left/right/both
position: both
suffix: 1
# When cover is not set, the default cover is displayed (當沒有設置cover時,默認的封面顯示)
default_cover:
https://api.aixiaowai.cn/api/api.php

如果文章没有指定封面,就使用默认封面,这里如果添加随机图片的api,是不是默认就随机的;

设置之后每一个文章封面都显示一样的图片。查看发送请求,只是发送了一次请求,那图片肯定只有一张,那接下来就是改造一下,让他多发送请求:

打开hexo根目录\themes\butterfly\scripts新建一个random_img.js文件。

将以下代码复制进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
}

打开butterfly主题配置文件:在cover:插入suffix: 1并保存(目的是在链接后面加入后缀?spm={随机数} 0是不使用后缀、1是?加随机数;2是&加随机数)

最后运行就可以了。查看接口,可以看到随机发送了多个请求。

一个小问题

在使用一些随机图片api的时候,会发现如果本身的站点是https协议的,而随机图片api不是,会导致手机端无法正常显示,这种情况只能换一个支持httpsAPI

参考链接:https://blog.mitsumune.top/2023/02/13/hexo_butterfly%E4%B8%BB%E9%A2%98%E6%B7%BB%E5%8A%A0%E5%AF%B9%E9%9A%8F%E6%9C%BA%E5%9B%BE%E7%89%87api%E7%9A%84%E6%94%AF%E6%8C%81/?

最终效果

博客链接:https://blog.mstudio.top