容器:
<div className="backTop" style={{ display: showTrue ? 'block' : 'none' }} onClick={backTop}>返回顶部</div>
样式:
.backTop {
position: fixed;
height: 40px;
width: 40px;
right: 10px;
bottom: 50px;
border-radius: 5px;
background-color: red;
color: white;
font-size: 14px;
text-align: center;
line-height: 20px;
transform: all 0.5s;
z-index: 2;
}
//容器样式
.div {
height: 300px;
width: 100%;
}
定义一个状态控制回顶按钮的显示与隐藏:
const [showTrue, setShowTrue] = useState(false)
useEffect(() => {
getGoodList()
const handleScrool = () => {
//滑动的距离大于 0 时,显示按钮
document.documentElement.scrollTop > 0 ? setShowTrue(true) : setShowTrue(false)
}
document.addEventListener('scroll', handleScrool)
return () => document.removeEventListener('scroll', handleScrool)
}, [showTrue])
点击按钮回到顶部:
// 回到顶部
const backTop = () => {
let timer = setInterval(() => {
//获取滑动的距离
let top = document.documentElement.scrollTop || document.body.scrollTop
window.scrollTo(0, top - top / 5) //设置返回时 是缓慢带有动画的
if (top === 0) {
clearInterval(timer)
}
}, 30)
}