功能:
拖动滚动条到一定的距离显示返回顶部
思路:
1.先写一个返回顶部盒子,固定到页面的某个位置。隐藏元素
2.监听滚动事件
3.滚动到指定位置显示
代码:
<div class="return-top">
返回顶部
</div>
var top = document.querySelector('.return-top') // 获取元素加过度效果 (用ref也可以)
window.addEventListener('scroll',()=>{
// 滚动大于500显示
if(document.documentElement.scrollTop > 500 ){
top.style.opacity = '1'
top.style.transition = 'all 1s'
}else{
top.style.opacity = '0'
top.style.transition = 'all 1s'
}
})