It has been 830 days since the last update, the content of the article may be outdated.
博客相关 hexo 美化【Hexo】文章封面添加随机图 API
AiGuoHou1  前言
在配置 butterfly 主题的时候发现一个问题,如果将主頁、文章封面的默认 top_img 配置为同一个随机图片 api 时会出现所有图片都相同的情况:

2  如何解决
最开始我的解决方案是配置多个随机图片 api:

用了一段时间后对随机的图片不是很满意,为了符合自己的 XP 就自己弄了个随机图片 api。然后就又回到了最开始的问题,刚好之前在浏览 Issues 的时候发现有人提交了个 PR 可惜并未通过。详细配置方法如下:
- 打开 hexo根目录\themes\butterfly\scripts新建一个 random_img.js 文件。

- 将以下代码复制进 random_img.js 文件并保存。
| 12
 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
 
 | 
 
 
 
 '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 是 & 加随机数)

- 最后运行以下命令查看是否生效:
| 1
 | hexo cl && hexo g && hexo s
 | 
