废话不多说直接看效果
1.首先是监听鼠标滚动到页面顶部的距离
在合适的距离让返回顶部的按钮显示出来
mounted() {
window.addEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll() {
//滚动条滚动时,距离顶部的距离
this.scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
// 判断是否下拉了所需长(高)度,若满足,则返回顶部图标出现
if (this.scrollTop > document.body.clientHeight - 50) {
this.isActive = true;
} else {
this.isActive = false;
}
},
}
2.显示出来后,添加点击事件,完成回到顶部操作
<script>
methods: {
//返回顶部
goTop() {
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);
},
}
</style>
完整代码如下:
<template>
<div id="app">
<h1>回到顶部组件</h1>
<div class="scrollBox" title="返回顶部" @click="goTop()" v-show="isActive">
<button class="primary-btn">
<div class="div_icon"></div>
<span class="primary-btn-text">顶部</span>
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isActive: false,
}
},
mounted() {
window.addEventListener("scroll", this.handleScroll);
},
methods: {
//返回顶部
goTop() {
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);
},
handleScroll() {
//滚动条滚动时,距离顶部的距离
this.scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
// 判断是否下拉了所需长(高)度,若满足,则返回顶部图标出现
if (this.scrollTop > document.body.clientHeight - 50) {
this.isActive = true;
} else {
this.isActive = false;
}
},
}
}
</script>
<style lang="less" scoped>
#app {
background: pink;
width: 100%;
height: 10000px;
}
.scrollBox {
width: 40px;
position: fixed;
left: 50%;
bottom: 60px;
z-index: 100;
margin-left: 530px;
width: 35px;
display: flex;
flex-direction: column;
justify-content: space-between;
text-align: center;
border-radius: 8px;
.primary-btn {
width: 35px;
padding: 3px 0 6px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border-radius: 8px;
font-size: 12px;
transform-origin: center;
transition: 0.2s;
border: 1px solid #e3e5e7;
background: transparent;
cursor: pointer;
.div_icon {
width: 0;
height: 0;
line-height: 0;
font-size: 0;
border: 5px solid transparent;
border-bottom-color: #000;
}
.primary-btn-text {
margin-top: 5px;
text-align: center;
font-size: 12px;
line-height: 14px;
}
&:hover {
background: #e3e5e7;
}
}
}
</style>