参考了安知鱼的方案进行修改
原教程butterfly 重装日记

闲聊

【个人博客网站】博客美化:制作右键菜单中,有一个功能一直有问题,那就是随便逛逛

这个功能实现的是随机文章显示,但因为我忽略了某些东西,导致该功能异常

安装

1
npm install hexo-generator-sitemap --save

这个插件是生成站点地图,用于随机访问文章

js

创建themes/butterfly/scripts/helpers/random.js文件

1
2
3
4
5
6
7
8
9
10
11
hexo.extend.generator.register('random', function (locals) {
const config = hexo.config.random || {}
const posts = []
for (const post of locals.posts.data) {
if (post.random !== false) posts.push(post.path)
}
return {
path: config.path || 'mengnianxiaoyao/random.js',
data: `var posts=${JSON.stringify(posts)};function toRandomPost(){window.open('/'+posts[Math.floor(Math.random() * posts.length)],"_self");};`
}
})

如果你开启了pjax,就用下面的代码

1
2
3
4
5
6
7
8
9
10
11
hexo.extend.generator.register('random', function (locals) {
const config = hexo.config.random || {}
const posts = []
for (const post of locals.posts.data) {
if (post.random !== false) posts.push(post.path)
}
return {
path: config.path || 'mengnianxiaoyao/random.js',
data: `var posts=${JSON.stringify(posts)};function toRandomPost(){pjax.loadUrl('/'+posts[Math.floor(Math.random() * posts.length)]);};`
}
})

配置

插件配置

在hexo配置文件或者主题配置文件中,添加以下内容

1
2
3
4
5
6
# 站点地图
sitemap:
path: sitemap.xml
rel: false
tags: true
categories: true

js配置

在主题配置文件中injectbuttom项导入

1
2
buttom:
- <script src="/mengnianxiaoyao/random.js"></script>

调用

在需要调用的位置执行toRandomPost()函数即可。

比如任意dom添加onclick="toRandomPost()"