vue中返回顶部封装的组件 滚动一定位置显示隐藏
用两个不同方式写的返回顶部
返回顶部子组件1
<template>
<div>
<div @click="backtop" class="fh" v-show="isShow">顶部1</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);
}
}, 10);
},
},
};
</script>
<style lang="scss" scoped>
.fh {
width: 50px;
height: 50px;
border: 1px solid;
position: fixed;
bottom: 50px;
left: 20px;
}
</style>
返回顶部子组件2
<template>
<div>
<!-- 使用超链接锚点定位回到顶部 没动画效果 -->
<div @click="back" class="back1" v-show="isShow">顶部2</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;
}
},
back() {
//返回顶部 $这个地方需要引入在线jq
$("html").stop().animate(
//animate:动画 点击时让它行动
{
scrollTop: 0, //距离顶部为0
},
1000 //多少时间完成行动
);
},
},
};
</script>
<style lang="scss" scoped>
.back1 {
width: 50px;
height: 50px;
border: 1px solid;
position: fixed;
bottom: 50px;
left: 183px;
}
</style>
父组件
<template>
<div class="about">
<ul>
<li v-for="(item, index) in 100" :key="index">{{ item }}</li>
</ul>
<a href="#">顶部3</a>
<FH1 />
<FH2 />
</div>
</template>
<script>
import FH1 from "../components/dingbu/FH1"; //导入
import FH2 from "../components/dingbu/FH2";
export default {
components: {
FH1,
FH2,
},
data() {
return {
};
},
methods: {
},
created() {
},
};
</script>
<style lang="scss" scoped>
ul {
margin: 0;
padding: 0;
}
li {
height: 50px;
border-bottom: 1px solid;
list-style: none;
margin: 0;
}
a {
width: 50px;
height: 50px;
border: 1px solid;
position: fixed;
bottom: 50px;
right: 20px;
}
</style>
效果