随机文章

  • 创建文件
    创建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:travelling() || fas fa-bus

随机友联代码

新建\butterfly\scripts\helpers random.js

添加函数
在主题下helpers中新建random.js文件,也就是themes/butterfly/scripts/helpers中新建random.js文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 随机友链
*/
hexo.extend.filter.register('after_render:html', function (data) {
const flinks = []
// 获取所有友链链接
hexo.locals.get('data').link.map(function (list) {
list.link_list.map(function (flink) {
flinks.push(flink.link)
})
})
// 随机获取一个友链
data += `<script>var flinks=${JSON.stringify(flinks)};function toRandomFlink(){window.open(flinks[Math.floor(Math.random()*flinks.length)]);};</script>`
return data
})

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

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

使用
使用这种东西就看自己了,只要在你想要实现友链跳转的地方添加onclick=”toRandomFlink()”即可。