前言

在现有的Butterfly主题中(4.12.0),还没有给默认文章封面添加随机的图片的配置,下面是一种解决方法:

将默认图片改为随机图片的API网址,让首页发送多次请求,达到首页封面随机的效果。

解决过程

_config.butterfly.yml文件中找到cover的配置项,default_cover是配置默认封面,把它修改为随机图片的网站。(这种网站百度搜索很多,最好是找有https的站点)

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

设置之后可以查看首页效果,这个时候会发现,首页封面用的都是同样的图片,这肯定不是最终想要的效果。打开控制台查看发送请求,发现图片请求只发送一次,那图片肯定只有一张,那接下来就是改造一下,让它多发送请求。

打开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
}

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

最后运行就可以了。查看首页,就会发现首页是随机的封面,查看接口,可以看到随机发送了多个请求。

一个小问题

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

参考链接:hexo butterfly主题添加对随机图片api的支持