在前一篇文章 Astro 部落格架設筆記(1) - 系統環境初始化 中,我們建立好 Astro 的開發環境後,接下來就可以從回到頁首 這個功能,熟悉一下整體環境。
我們就先從一個小功能來實踐,透過 ,來熟悉整個環境。當使用者滾動畫面後,會出現回到頁首的圖示,按下去後就自動滾到頁首。
首先,新增一個 BackToTop.astro 元件,來實作回到頁首的功能
<button id="back-to-top" class="back-to-top" aria-label="回到頁首">↑</button>
<style>
.back-to-top {
position: fixed;
bottom: 1rem;
right: 1rem;
width: 3rem;
height: 3rem;
font-size: 1.5rem;
background-color: #0077ff;
color: white;
border: none;
border-radius: 50%;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
cursor: pointer;
display: none; /* 初始隱藏 */
align-items: center;
justify-content: center;
z-index: 1000;
transition: opacity 0.3s ease;
}
.back-to-top.show {
display: flex;
}
</style>
<script>
const btn = document.getElementById('back-to-top');
const showAfter = 300; // 滾動超過 300px 才顯示
window.addEventListener('scroll', () => {
if (window.scrollY > showAfter) {
btn.classList.add('show');
} else {
btn.classList.remove('show');
}
});
btn.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
</script>
接下來修改 BlogPost.astro 將我們前面寫好的元件 import 即可
---
import BackToTop from "../components/BackToTop.astro";
---
<main>
<article>
...
</article>
<BackToTop/>
</main>
每一個 astro 檔案就是一塊塊的積木,寫好的每一個元件可以在別的地方重複使用。
BlogPost.astro 這個檔案的用途是用來顯示文章內容以外的部分,除此之外還可以調整標題、外框等等資訊。
大致了解這樣的運作模式後,就可以做更進一步的開發了。
0 意見:
張貼留言