feat: 添加“返回顶部”组件,提升用户导航体验
Some checks failed
Deploy docs for Site / deploy (20.x) (push) Has been cancelled
Some checks failed
Deploy docs for Site / deploy (20.x) (push) Has been cancelled
This commit is contained in:
46
src/components/ui/back-to-top.tsx
Normal file
46
src/components/ui/back-to-top.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import { ArrowUp } from "lucide-react";
|
||||
import { Button } from "./button";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function BackToTop() {
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const toggleVisibility = () => {
|
||||
if (window.scrollY > 300) {
|
||||
setIsVisible(true);
|
||||
} else {
|
||||
setIsVisible(false);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("scroll", toggleVisibility);
|
||||
return () => window.removeEventListener("scroll", toggleVisibility);
|
||||
}, []);
|
||||
|
||||
const scrollToTop = () => {
|
||||
window.scrollTo({
|
||||
top: 0,
|
||||
behavior: "smooth",
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`fixed bottom-8 right-8 z-50 transition-all duration-300 ${
|
||||
isVisible
|
||||
? "translate-y-0 opacity-100"
|
||||
: "translate-y-4 opacity-0 pointer-events-none"
|
||||
}`}
|
||||
>
|
||||
<Button
|
||||
size="icon"
|
||||
onClick={scrollToTop}
|
||||
className="rounded-full shadow-lg bg-primary/90 backdrop-blur-sm border border-border/50 hover:bg-primary hover:shadow-xl hover:-translate-y-1 transition-all h-10 w-10"
|
||||
>
|
||||
<ArrowUp className="h-5 w-5 text-primary-foreground" />
|
||||
<span className="sr-only">Back to top</span>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
import BackToTop from "@/components/ui/back-to-top";
|
||||
import { useTranslations } from "@/i18n/utils";
|
||||
import type { Lang } from "@/types/i18n";
|
||||
import { defaultLang } from "@/i18n/ui";
|
||||
@@ -44,6 +45,7 @@ const t = useTranslations(lang);
|
||||
>
|
||||
</div>
|
||||
<slot />
|
||||
<BackToTop client:load />
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user