<template>
<div v-show="isShow" @click="handleClick">
返回顶部
</div>
</template>
<script>
import throttle from 'throttle-debounce/throttle'
export default {
name: 'SideBar',
props: {
visibilityHeight: {
type: Number,
required: false,
default: 150
}
},
data () {
return {
el: null,
container: null,
isShow: false
}
},
mounted () {
this.init()
this.throttledScrollHandler = throttle(300, this.onScroll)
this.container.addEventListener('scroll', this.throttledScrollHandler)
},
methods: {
init () {
this.container = document
this.el = document.documentElement
},
handleClick (index) {
this.scrollToTop()
},
onScroll () {
const scrollTop = this.el.scrollTop
this.isShow = scrollTop >= this.visibilityHeight
},
scrollToTop () {
let el = this.el
let step = 0
let interval = setInterval(() => {
if (el.scrollTop <= 0) {
clearInterval(interval)
return
}
step += 10
el.scrollTop -= step
}, 20)
}
}
}
</script>
网友评论