新建文件

  • 创建themes/butterfly/scripts/helpers/random.js文件
  • 开启pjax

1
2
3
4
5
6
7
8
9
10
11
12
13
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 || "sam/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
12
13
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 || "sam/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="/sam/random.js"></script>

调用

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

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

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

  • 张洪大佬

  • 安知鱼大佬