回到顶部
<div ref='home'></div>
<span class="hui" v-show="huiShow" @click="huiTop">回到顶部</span>
1. 首先获取最外层盒子的dom
2. 监听这个盒子的滚动事件
mounted() {
this.$refs.home.addEventListener('scroll',this.handlerscroll)
},
destroyed(){
this.$refs.home.removeEventListener('scroll',this.handlerscroll)
},
methods: {
huiTop() {
this.$refs.home.scroll({
top:0,
// 控制向上的时候是缓慢的向上移动
behavior:'smooth'
})
},
handlerscroll() {
// Math.ceil向上取整 距离顶部的高度如果大于100 就让回到顶部span显示 否则隐藏
if(Math.ceil(this.$refs.home.scrollTop) >= 100) {
this.huiShow = true
} else {
this.huiShow = false
}
}