Files
aurora-admin/frameworks/BackToTop.jsx
T

52 lines
1.6 KiB
React

import React, { useEffect, useState } from 'react';
import './BackToTop.css';
export default function BackToTop({ threshold = 400, showRing = true }) {
const [visible, setVisible] = useState(false);
const [progress, setProgress] = useState(0);
const r = 20;
const circumference = 2 * Math.PI * r;
const offset = circumference * (1 - progress);
useEffect(() => {
function onScroll() {
const st = window.pageYOffset || document.documentElement.scrollTop;
const max = document.documentElement.scrollHeight - window.innerHeight;
setProgress(max > 0 ? st / max : 0);
setVisible(st > threshold);
}
window.addEventListener('scroll', onScroll, { passive: true });
onScroll();
return () => window.removeEventListener('scroll', onScroll);
}, [threshold]);
function toTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
return (
<div
className={'aa-backtop' + (visible ? ' is-visible' : '') + (showRing ? '' : ' aa-no-ring')}
role="button"
aria-label="返回顶部"
onClick={toTop}
>
{showRing ? (
<svg viewBox="0 0 44 44">
<circle className="aa-backtop-ring-bg" cx="22" cy="22" r="20" fill="none" strokeWidth="2" />
<circle
className="aa-backtop-ring-fg"
cx="22"
cy="22"
r="20"
fill="none"
strokeWidth="2"
style={{ strokeDasharray: circumference, strokeDashoffset: offset }}
/>
</svg>
) : null}
<span className="aa-backtop-arrow">↑</span>
</div>
);
}