feat: 返回顶部
This commit is contained in:
66
src/components/BackTop.astro
Normal file
66
src/components/BackTop.astro
Normal 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>
|
||||
Reference in New Issue
Block a user