feat: 返回顶部

This commit is contained in:
2026-07-18 21:48:21 +08:00
parent f77f8d13d1
commit aa4da842d6
4 changed files with 69 additions and 0 deletions

View File

@@ -0,0 +1,66 @@
---
import {Image} from "astro:assets";
import backTopIcon from "../assets/icon/back-top.svg";
---
<button class="back-top" type="button" aria-label="返回顶部" hidden>
<Image src={backTopIcon} alt=""/>
</button>
<script>
const backTop = document.querySelector<HTMLButtonElement>(".back-top")
const toggleBackTop = () => {
if (!backTop) return;
backTop.hidden = window.scrollY <= 500;
};
backTop && backTop.addEventListener("click", () => {
window.scrollTo({
top: 0,
behavior: "smooth",
});
});
window.addEventListener("scroll", toggleBackTop, {passive: true});
toggleBackTop();
</script>
<style>
.back-top {
position: fixed;
right: 150px;
bottom: 100px;
width: 44px;
height: 44px;
z-index: 999;
cursor: pointer;
padding: 0;
border: none;
background: transparent;
}
.back-top[hidden] {
display: none;
}
.back-top :global(img) {
width: 100%;
height: 100%;
display: block;
}
.back-top:focus-visible {
outline: 2px solid currentColor;
outline-offset: 4px;
}
@media (max-width: 768px) {
.back-top {
right: 24px;
bottom: 48px;
}
}
</style>