<template>
<div>
<div @click="backtop" class="fh" v-show="isShow">返回顶部</div>
</div>
</template>
<script>
export default {
data() {
return {
isShow: false,
};
},
mounted() {
this.listenerFunction();
},
methods: {
listenerFunction(e) {
document.addEventListener("scroll", this.handleScroll, true);
},
beforeDestroy() {
document.removeEventListener("scroll", this.listenerFunction);
},
handleScroll() {
// handleScroll 和 methods 是同级
if (window.pageYOffset > 300) {
//window.pageYOffset:获取滚动距离
this.isShow = true;
} else {
this.isShow = false;
}
},
//返回顶部
backtop() {
let top = document.documentElement.scrollTop || document.body.scrollTop;
// 实现滚动效果
const timeTop = setInterval(() => {
document.body.scrollTop = document.documentElement.scrollTop = top -= 50;
if (top <= 0) {
clearInterval(timeTop);
}
}, 20);
},
},
};
</script>
<style lang="scss" scoped>
.fh {
width: 50px;
height: 50px;
border: 1px solid;
position: fixed;
right:0;
bottom: 50px;
}
</style>
Vue中封装返回顶部功能
最新推荐文章于 2023-03-31 19:36:38 发布