很多網站都有隨機頁面的功能,比如維基百科,點下去會隨機跳轉到一個頁面。
看到Wiwi.Blog的random頁面覺得有趣,便想跟著做一個。
我遇到的問題是寫的文章的太多了,有的我已經不知道怎麼整理了。不如用這個方法製造驚喜。
1. 預期目標#
具體效果請參訪:隨機頁面 - Ivon的部落格
使用者進入一個特製頁面,讀完指示,開始隨機跳轉到本站的一篇文章。
然後跳到另外一個頁面,在那個頁面進行倒數,才進行跳躍。為了提昇中二感,這個頁面叫做「命運石之門的選擇」。
跳轉過程可以取消,但是取消了有懲罰。
包含的頁面內容應該涵蓋Hugo的content目錄下所有section的文章。
2. 實作#
因為我對這方面不太熟,所以有用到一點vibe coding的建議。
新增
layouts/pages/random-post.html,這是特製頁面要使用的模板內容如下,讀取所有content目錄下的文章,即
.Site.RegularPages
{{ define "main" }}
{{ .Content }}
<div class="container">
<p class="message">正在跳轉到隨機文章......</p>
<div class="countdown" id="countdown">3</div>
<button class="cancel-btn" id="cancelBtn">取消跳轉</button>
</div>
<script>
(function() {
const posts = [
{{ range .Site.RegularPages }}
"{{ .Permalink }}",
{{ end }}
];
if (posts.length === 0) {
document.querySelector('.message').textContent = '沒有找到文章';
document.getElementById('countdown').style.display = 'none';
document.getElementById('cancelBtn').style.display = 'none';
return;
}
const randomIndex = Math.floor(Math.random() * posts.length);
const randomPost = posts[randomIndex];
let secondsLeft = 3;
const countdownElement = document.getElementById('countdown');
const cancelBtn = document.getElementById('cancelBtn');
let cancelled = false;
countdownElement.textContent = secondsLeft;
const countdownInterval = setInterval(function() {
secondsLeft--;
if (secondsLeft > 0) {
countdownElement.textContent = secondsLeft;
} else {
clearInterval(countdownInterval);
if (!cancelled) {
window.location.replace(randomPost);
}
}
}, 1000);
cancelBtn.addEventListener('click', function() {
cancelled = true;
clearInterval(countdownInterval);
window.location.href = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
/*
document.querySelector('.message').textContent = '已取消跳轉';
countdownElement.style.display = 'none';
cancelBtn.textContent = '返回上一頁';
cancelBtn.onclick = function() {
window.history.back();
};
*/
});
})();
</script>
{{ end }}
- 新增
content/random-post/index.md,作為說明頁面。這個頁面在站內的網址會變成/random-posts/
---
title: "隨機頁面"
description: ""
---
點選以下按鈕,隨機跳轉到本站的一篇文章,可能會有意外的驚喜!內容可能是一個實用軟體的教學文,也可能是好康的圖片,也可能是我的深夜murmur。
<a href="/steins-gate-choice/" class="btn">🎲 隨機閱讀 🎲</a>
警告:這裡會遍歷全站的文章,沒有進行過濾,可能會看到不堪入目的內容,請謹慎使用!
為什麼做這個頁面:因為寫的文章的太多了,有的我已經不知道怎麼整理了。
- 新增
content/random-post/index.md,引用上面寫好的random-post.html模板,作為實際跳轉頁面,加入一段中二文字提昇神秘感。這個頁面在站內的網址會變成/steins-gate-choice/。我原本想寫一個跳轉時候畫面扭曲的動畫效果,可是太複雜就放棄了。
---
title: "這一切都是命運石之門的選擇——"
description: ""
layout: "random-post"
---
<!--從random-post頁面跳轉過來 -->
There is no end though there is a start in space. — Infinite. It has (its) own power, it ruins, and it goes though there is a start also in the star. — Finite. Only the person who (has) wisdom can read the most foolish one from the history. The fish that lives in the sea doesn't know the world in the land. It also ruins and goes if they have wisdom. It is funnier that man exceeds the speed of light than fish start living in the land. It can be said that this is (a) final ultimatum from the god to the people who can fight.