Hexo 博客随机封面图脚本
之前 Hexo 博客(Kratos Rebirth 主题)使用的文章封面随机图片脚本,记录两种实现方式。
本地资源版
从主题自带的 thumb 图片中随机选取,通过去重机制避免相邻文章封面重复。
js
(() => {
const defaultCoverSrc = "/images/default.webp";
const randomImageSrcTemplate = "https://www.unpkg.com/hexo-theme-kratos-rebirth@2.2.0/source/images/thumb/thumb_{no}.webp";
const randomImageCount = 20;
const usedImages = new Array(randomImageCount);
const generateNewCoverID = () => {
let remailFailCounts = 2;
let imageNo;
while (remailFailCounts > 0) {
imageNo = Math.floor(Math.random() * randomImageCount);
if (!usedImages[imageNo]) {
break;
} else {
remailFailCounts--;
}
}
if (remailFailCounts <= 0) {
imageNo = -1;
for (let i = 0; i < randomImageCount; i++) {
if (!usedImages[i]) {
imageNo = i;
break;
}
}
if (imageNo === -1) {
for (let i = 0; i < randomImageCount; i++) {
usedImages[i] = false;
}
imageNo = Math.floor(Math.random() * randomImageCount);
}
}
usedImages[imageNo] = true;
return imageNo + 1;
}
const randAll = () => {
const allDefaultImageEls = document.querySelectorAll(`img.kratos-entry-thumb-img[src='${defaultCoverSrc}']`);
for (const el of allDefaultImageEls) {
el.setAttribute('src', randomImageSrcTemplate.replace("{no}", generateNewCoverID().toString()));
}
}
randAll();
window.addEventListener('pjax:complete', randAll);
})()1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
在线 API 版
通过 API 获取随机图片 URL 列表并缓存,每次从缓存中随机选取。
js
const randomImageCache = [];
const defaultCoverSrc = "/images/default.webp";
const randomImageCount = 20;
async function getRandomOnlineImageUrlList() {
const randomOnlineImageQueryApi = `https://t.alcy.cc/ycy?json&quantity=${randomImageCount}`;
try {
const resp = await fetch(randomOnlineImageQueryApi);
const randomImageSrcs = await resp.text();
const randomImageSrcList = randomImageSrcs.split("\n");
randomImageCache.push(...randomImageSrcList);
} catch (error) {
console.log(error);
}
}
function getRandomCoverSrc() {
if (randomImageCache.length) {
return randomImageCache[Math.floor(Math.random() * randomImageCount)];
} else {
return defaultCoverSrc;
}
}
function randAll() {
const allDefaultImageEls = document.querySelectorAll(`img.kratos-entry-thumb-img[src='${defaultCoverSrc}']`);
for (const el of allDefaultImageEls) {
el.setAttribute('src', getRandomCoverSrc());
}
}
(async () => {
await getRandomOnlineImageUrlList();
randAll();
window.addEventListener("pjax:complete", randAll);
})();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41