62 lines
1.4 KiB
TypeScript
62 lines
1.4 KiB
TypeScript
"use client"
|
|
|
|
import { useEffect, useState } from 'react'
|
|
|
|
export function ScrollToTop() {
|
|
const [isVisible, setIsVisible] = useState(false)
|
|
|
|
const toggleVisibility = () => {
|
|
if (window.scrollY > 300) {
|
|
setIsVisible(true)
|
|
} else {
|
|
setIsVisible(false)
|
|
}
|
|
}
|
|
|
|
const scrollToTop = () => {
|
|
window.scrollTo({
|
|
top: 0,
|
|
behavior: 'smooth'
|
|
})
|
|
}
|
|
|
|
useEffect(() => {
|
|
window.addEventListener('scroll', toggleVisibility)
|
|
return () => {
|
|
window.removeEventListener('scroll', toggleVisibility)
|
|
}
|
|
}, [])
|
|
|
|
return (
|
|
<>
|
|
{isVisible && (
|
|
<button
|
|
onClick={scrollToTop}
|
|
className="fixed bottom-8 right-8 p-3 rounded-full shadow-lg
|
|
bg-white dark:bg-gray-800
|
|
hover:bg-gray-100 dark:hover:bg-gray-700
|
|
text-gray-800 dark:text-gray-200
|
|
ring-1 ring-gray-200 dark:ring-gray-700
|
|
transition-all duration-300
|
|
z-50"
|
|
aria-label="回到顶部"
|
|
>
|
|
<svg
|
|
xmlns="http://www.w3.org/2000/svg"
|
|
className="h-5 w-5"
|
|
fill="none"
|
|
viewBox="0 0 24 24"
|
|
stroke="currentColor"
|
|
>
|
|
<path
|
|
strokeLinecap="round"
|
|
strokeLinejoin="round"
|
|
strokeWidth={2}
|
|
d="M5 10l7-7m0 0l7 7m-7-7v18"
|
|
/>
|
|
</svg>
|
|
</button>
|
|
)}
|
|
</>
|
|
)
|
|
}
|