65 lines
2.1 KiB
React
65 lines
2.1 KiB
React
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 (
|
|
<button
|
|
onClick={scrollToTop}
|
|
title="返回顶部"
|
|
aria-label="返回顶部"
|
|
className="fixed bottom-20 md:bottom-6 right-4 md:right-6 z-40 w-12 h-12 rounded-full bg-blue-600 hover:bg-blue-700 text-white shadow-lg shadow-blue-600/40 hover:shadow-blue-600/60 flex items-center justify-center transition-all hover:-translate-y-0.5 active:translate-y-0"
|
|
>
|
|
<Rocket size={22} className="-rotate-45" />
|
|
</button>
|
|
);
|
|
}
|
|
|
|
export default BackToTop;
|