Files
gitlab-instance-0a899031_na…/app/components/ScrollToTop.tsx
2025-11-13 05:05:53 +08:00

41 lines
823 B
TypeScript

'use client'
import { useEffect, useState } from 'react'
export function ScrollToTop() {
const [isVisible, setIsVisible] = useState(false)
// 检查滚动位置
const toggleVisibility = () => {
if (window.pageYOffset > 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 (
<button
className={`scroll-to-top ${isVisible ? 'show' : ''}`}
onClick={scrollToTop}
aria-label="Scroll to top"
>
<i className="fas fa-arrow-up"></i>
</button>
)
}