想要给博客增加一些趣味性?让读者可以随机浏览你的文章是个不错的选择。本文将详细介绍如何在Hexo博客中实现随机文章功能,就跟本博客的侧栏导航中的【手气】菜单一样的效果。
1. 功能介绍
随机文章功能可以让访问者随机浏览博客中的任意一篇文章,这不仅能增加博客的趣味性,还能提高文章的曝光率,让一些早期的优质文章也有机会被读者发现。
2. 实现步骤
2.1 创建模板文件
首先在主题的layout
目录下创建random.ejs
文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <% // 获取所有文章 const posts = site.posts.data; // 随机选择一篇文章 const randomPost = posts[Math.floor(Math.random() * posts.length)]; %>
<script> // 立即重定向到随机文章 window.location.href = '<%- url_for(randomPost.path) %>'; </script>
<noscript> <div style="text-align: center; padding: 20px;"> <p>请点击下方链接访问随机文章:</p> <a href="<%- url_for(randomPost.path) %>"><%- randomPost.title %></a> </div> </noscript>
|
2.2 创建页面文件
在source
目录下创建random
文件夹,并在其中创建index.md
:
1 2 3 4 5 6 7
| --- title: 随机文章 date: 2023-12-31 12:00:00 type: random layout: random comments: false ---
|
2.3 添加菜单项
在主题的_config.yml
中添加菜单项:
1 2 3 4 5
| menu: random: path: /random text: 手气 icon: fas fa-random
|
3. 功能说明
3.1 工作原理
- 当访问者点击”随机文章”菜单时,会访问
/random
页面
- 模板会从所有文章中随机选择一篇
- 通过JavaScript自动跳转到选中的文章
- 如果浏览器禁用了JavaScript,则显示一个可点击的链接
3.2 优化建议
- 性能优化: 如果博客文章很多,可以考虑缓存文章列表
- 用户体验: 可以添加加载动画
- 功能扩展: 可以按分类或标签随机
4. 常见问题
4.1 页面闪烁
如果出现页面闪烁,可以添加loading效果:
1 2 3 4 5 6 7 8 9 10 11
| <style> .loading { text-align: center; padding: 20px; } .loading:after { content: '正在随机选择文章...'; color: #666; } </style> <div class="loading"></div>
|
4.2 重复访问
如果想避免连续访问同一篇文章,可以使用sessionStorage记录历史:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const history = JSON.parse(sessionStorage.getItem('randomHistory') || '[]');
const availablePosts = posts.filter(post => !history.includes(post.path));
if (availablePosts.length === 0) { sessionStorage.removeItem('randomHistory'); availablePosts = posts; }
const randomPost = availablePosts[Math.floor(Math.random() * availablePosts.length)];
history.push(randomPost.path); sessionStorage.setItem('randomHistory', JSON.stringify(history));
|
5. 总结
随机文章功能虽然实现简单,但能大大提升博客的趣味性和用户体验。你还可以基于这个基础功能,添加更多个性化的扩展,比如按照文章热度随机、按照阅读时间随机等。
如果觉得文章对你有帮助,欢迎点赞、评论、分享,你的支持是我继续创作的动力!