Files
blog/source/_posts/2025.08/go-to-random-page.md
2025-08-26 13:20:20 +08:00

1.8 KiB
Raw Blame History

title, tags, categories, series, cover, abbrlink, summary, date
title tags categories series cover abbrlink summary date
利用 SiteMap 随机访问站内页面 网站 建站手札 webcustom https://pic.biss.click/i/2025/08/26/200711.webp b5866b9e 提供了一个很好的解决方案,通过使用 Hexo 的 sitemap 生成器和 JavaScript 代码来实现随机访问站内页面的功能 以下是你提供的步骤的详细解释: 2025-08-12 15:15:32

在网上查找博客美化过程时发现基本上都有“随便逛逛”的功能,于是自己也添加一个。 比较简单只有js代码但是先要安装插件

前置条件

npm install hexo-generator-sitemap --save

在站点配置文件 _config.yaml中添加:

sitemap:
  path: 
    - sitemap.xml
    - sitemap.txt
  rel: false
  tags: true
  categories: true

添加js

在主题目录下添加·\themes\butterfly\source\js\random.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
    })
}

使用

使用,在菜单栏上添加

<a href="javascript:;" onclick="randomPost()" title="随机访问一篇文章">随机</a>

参考

{% link 木木木木木的博客,木木木木木,https://immmmm.com/randompost-by-sitemap/ %}