当前位置 博文首页 > 你见过思念放过谁的博客:vue 返回顶部动画效果
小程序、前端交流群:609690978
methods: {
// 监听页面滚动
scrollToTop() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
this.showTopTimer && clearTimeout(this.showTopTimer)
this.showTopTimer = setTimeout(() => {
this.handleScrollEnd()
}, 300)
this.currentTop = scrollTop
this.showTop = false
},
// 停止滚动时触发
handleScrollEnd() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
if (scrollTop === this.currentTop && scrollTop > document.documentElement.clientHeight) {
this.showTop = true
clearTimeout(this.showTopTimer)
}
},
// 返回顶部动画效果
toTop() {
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
// 实现滚动效果
let speed = scrollTop / 10 // 每次滚动多少 (步长值)
const timeTop = setInterval(() => {
if (document.documentElement.scrollTop !== 0) {
document.documentElement.scrollTop -= speed // 不在顶部 每次滚动到的位置
} else {
clearInterval(timeTop) // 回到顶部清除定时器
}
}, 20)
},
},
// 退出页面时取消监听
beforeDestroy() {
window.removeEventListener('scroll', this.scrollToTop)
}
cs