配置butterfly主题时,如果想设置随机封面,会发生这么一种情况,就是有些文章封面图片都是同一张,如下所示:
解决方案
在博客更目录/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
|
'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:
选项如下:
- 0 不使用后缀
- 1 ?加随机数
- 2 &加随机数