提到随机网页跳转,大家就想到hexo-generator-random,我之前也是使用这个插件来做随机网页,这个插件的原理是生成一个html,只要访问这个html就可以进入随机的文章,但是这种方法有问题。

  • 开启pjax的小伙伴由于random.html不支持pjax,导致中间页会重新加载两次
  • 进入随机页面之后无法使用后退回到上个页面。

看了@JAYHRN的教程Hexo 博客实现页面随机跳转之后,他是使用Hexo函数直接生成,那么为什么不能用这种方法生成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 || 'zhheo/random.js',
data: `var posts=${JSON.stringify(posts)};function toRandomPost(){pjax.loadUrl('/'+posts[Math.floor(Math.random() * posts.length)]);};`
}
})

如果你没有开启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 || 'zhheo/random.js',
data: `var posts=${JSON.stringify(posts)};function toRandomPost(){window.open('/'+posts[Math.floor(Math.random() * posts.length)],"_self");};`
}
})

在主题配置文件引入themes/butterfly/_config.yml,inject的bottom里添加

1
<script src="/zhheo/random.js"></script>

调用

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

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

例如在配置文件导航栏中需要的位置添加,随机文章: javascript:toRandomPost() || fas fa-bus