diff --git a/source/_posts/go-to-random-page.md b/source/_posts/go-to-random-page.md new file mode 100644 index 0000000..a8ee24e --- /dev/null +++ b/source/_posts/go-to-random-page.md @@ -0,0 +1,53 @@ +--- +title: 利用 SiteMap 随机访问站内页面 +tags: 网站 +categories: 建站手札 +series: webcustom +abbrlink: b5866b9e +summary: >- + 提供了一个很好的解决方案,通过使用 Hexo 的 sitemap 生成器和 JavaScript 代码来实现随机访问站内页面的功能 + 以下是你提供的步骤的详细解释: +date: 2025-08-12 15:15:32 +--- + +{% series webcustom %} +在网上查找博客美化过程时发现基本上都有“随便逛逛”的功能,于是自己也添加一个。 +比较简单只有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 +随机 +``` +# 参考 +{% link 木木木木木的博客,木木木木木,https://immmmm.com/randompost-by-sitemap/ %} \ No newline at end of file