1、准备几个容器(模拟页面)
<div className="div" style={{ background: "red" }}></div>
<div className="div" style={{ background: "green" }}></div>
<div className="div" style={{ background: "white" }}></div>
<div className="div" style={{ background: "blue" }}></div>
<div className="backTop" style={{ display: showTrue ? 'block' : 'none' }} onClick={backTop}>返回顶部</div>
bakcTop:是回到顶部的按钮,绑定了一个点击事件
2、写一些样式
//回到顶部按钮样式
.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%;
}
3、在 useEffect 这个hook中,监听一个滚动事件
设置一个状态控制回到顶部按钮显示与隐藏
const [show, setShow] = useState(false)
useEffect(() => {
const handleScrool = () => {
//滑动的距离大于 0 时,显示按钮
document.documentElement.scrollTop > 0 ? setShowTrue(true) : setShowTrue(false)
}
document.addEventListener('scroll', handleScrool)
return () => document.removeEventListener('scroll', handleScrool)
}, [showTrue])
4、点击按钮回到顶部
// 回到顶部
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)
}