vue 之返回顶部组件
backTop.vue
<template>
<div class="floating" @click="goTop()" v-show="btnFlag">
<a href="javascript:;">
<em class="icon-text">回顶部</em>
</a>
</div>
</template>
<script>
export default {
props: ["refEle", "backTime"],
data() {
return {
btnFlag: false,
};
},
mounted() {
window.addEventListener("scroll", this.isShowBtn, true);
},
destroyed() {
window.removeEventListener("scroll", this.isShowBtn, true);
},
methods: {
goTop() {
// 拿到当前 需要滚动的节点 距离顶部多少距离
// console.log('ref节点',this.refEle,this.refEle.scrollTop);
this.timer = setInterval(() => {
let scrollTop = this.refEle.scrollTop;
let ispeed = Math.floor(-scrollTop / 5);
// console.log("速度和高度", ispeed, scrollTop);
this.refEle.scrollTop = scrollTop + ispeed;
if (scrollTop === 0) {
// console.log("到0了");
clearInterval(this.timer);
}
}, this.backTime);
},
isShowBtn() {
let scrollTop = "";
if (this.refEle) {
scrollTop = this.refEle.scrollTop;
} else {
scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
}
if (scrollTop > 60) {
this.btnFlag = true;
} else {
this.btnFlag = false;
}
},
},
};
</script>
<style scoped>
.floating {
width: 0.65rem;
position: fixed;
z-index: 1600;
right: 0.2rem;
bottom: 1rem;
}
.floating a {
text-decoration: none;
margin-bottom: 0.05rem;
display: block;
opacity: 0.9;
background-color: rgb(130, 130, 130);
}
.floating a:hover {
background-color: #33AAFF;
}
</style>
home.vue引用
<main ref="selfCon></main>
<BackTop
class="back_top"
:refEle="this.$refs.selfCon"
:backTime="30"
></BackTop>