vue下返回顶部功能实现,超过可视区域返回顶部按钮显示,否则隐藏。
<span v-if="btnFlag" class="go-top" @click="backTop"></span>
data(){
return {
btnFlag:false
}
},
// vue的两个生命钩子,这里不多解释。
// window对象,所有浏览器都支持window对象。它表示浏览器窗口,监听滚动事件
created () {
window.addEventListener('scroll', this.scrollToTop)
},
destroyed () {
window.removeEventListener('scroll',()=>{
this.scrollToTop();
});
}
methods: {
// 点击返回顶部方法
backTop () {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
},
scrollToTop () {
// 计算浏览器视口高度,当高度大于浏览器视口显示回顶部按钮,小于则隐藏
const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
const h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
if (scrollTop > h) {
this.btnFlag = true;
} else {
this.btnFlag = false;
}
}
}
这里返回顶部使用了javascript平滑滚动Element.scrollIntoView()。