Files
blog/source/_posts/2025/2025.08/go-to-random-page.md
2026-02-07 19:17:19 +08:00

65 lines
1.8 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: 利用 SiteMap 随机访问站内页面
tags: 网站
categories: 建站手札
series: webcustom
cover: https://pic.biss.click/image/2f13dc34-ccef-46f9-96d9-531e049fede5.webp
abbrlink: b5866b9e
summary: >-
提供了一个很好的解决方案,通过使用 Hexo 的 sitemap 生成器和 JavaScript 代码来实现随机访问站内页面的功能
以下是你提供的步骤的详细解释:
date: 2025-08-12 15:15:32
---
在网上查找博客美化过程时发现基本上都有“随便逛逛”的功能,于是自己也添加一个。
比较简单只有js代码但是先要安装插件
# 前置条件
```bash
npm install hexo-generator-sitemap --save
```
在站点配置文件 `_config.yaml`中添加:
```yml
sitemap:
path:
- sitemap.xml
- sitemap.txt
rel: false
tags: true
categories: true
```
# 添加js
在主题目录下添加·`\themes\butterfly\source\js\random.js`
```js
function randomPost() {
fetch('/sitemap.xml').then(res => res.text()).then(str => (new window.DOMParser()).parseFromString(str, "text/xml")).then(data => {
let ls = data.querySelectorAll('url loc');
let locationHref,locSplit;
do {
locationHref = ls[Math.floor(Math.random() * ls.length)].innerHTML
locSplit = locationHref.split('/')[3] || ''
} while (locSplit == '' || locSplit == 'tags');
//若所有文章都如 https://…….com/posts/2022/07/…… 格式,主域名后字符是 posts则循环条件改为
//while (locSplit !== 'posts');
location.href = locationHref
})
}
```
# 使用
使用,在菜单栏上添加
```html
<a href="javascript:;" onclick="randomPost()" title="随机访问一篇文章">随机</a>
```
# 参考
{% link 木木木木木的博客,木木木木木,https://immmmm.com/randompost-by-sitemap/ %}