import { useEffect, useState, useCallback } from 'react'; import { Rocket } from 'lucide-react'; /** * 返回顶部小火箭(右下角) * 兼容两种滚动容器:react-window 虚拟列表(内部滚动)和普通 overflow-y-auto 容器。 */ function findScrolledElement() { const all = document.querySelectorAll('*'); let best = null; let bestTop = 0; for (const el of all) { const style = window.getComputedStyle(el); const scrollable = (style.overflowY === 'auto' || style.overflowY === 'scroll') && el.scrollHeight > el.clientHeight + 4; if (scrollable && el.scrollTop > bestTop) { bestTop = el.scrollTop; best = el; } } return bestTop > 0 ? best : null; } function BackToTop() { const [visible, setVisible] = useState(false); useEffect(() => { const onScroll = () => { const el = findScrolledElement(); const top = el ? el.scrollTop : (window.scrollY || document.documentElement.scrollTop || 0); setVisible(top > 300); }; onScroll(); window.addEventListener('scroll', onScroll, true); window.addEventListener('resize', onScroll); const timer = setInterval(onScroll, 1500); return () => { window.removeEventListener('scroll', onScroll, true); window.removeEventListener('resize', onScroll); clearInterval(timer); }; }, []); const scrollToTop = useCallback(() => { const el = findScrolledElement(); if (el) el.scrollTo({ top: 0, behavior: 'smooth' }); window.scrollTo({ top: 0, behavior: 'smooth' }); document.documentElement.scrollTo({ top: 0, behavior: 'smooth' }); }, []); if (!visible) return null; return ( ); } export default BackToTop;