![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1517541c272af7329c7f931f0e37fce3.gif)
- 获取滚动距离 判断是否回到顶部
data() {
return {
scrollNum: 0,
isTop: false,
myTimer: -1,
};
},
mounted() {
window.addEventListener("scroll", () => {
let top =
document.documentElement.scrollTop ||
document.body.scrollTop ||
window.pageYOffset;
this.scrollNum = top;
if (top >= 100) {
this.isTop = true;
} else {
this.isTop = false;
}
});
},
- 回到顶部按钮 div
<div
class="goTop iconfont ml-gotop"
:class="isTop ? 'goTopAfter' : ''"
@click="goTop()"
></div>
- 回到顶部方法
goTop() {
if (this.myTimer == -1) {
this.myTimer = setInterval(() => {
this.scrollNum -= 60;
if (this.scrollNum <= 0) {
this.scrollNum = 0;
window.clearInterval(this.myTimer);
this.myTimer = -1;
}
window.scrollTo(0, this.scrollNum);
}, 10);
}
},
- 按钮样式
.goTop {
position: fixed;
bottom: -100px;
right: 5%;
width: 60px;
height: 60px;
border-radius: 30px;
z-index: 10;
background-color: rgba(33, 81, 129, 0.5);
transition: 0.3s ease-in-out;
font-size: 30px;
text-align: center;
line-height: 60px;
color: #ffffff;
transition: 0.3s ease-in-out;
cursor: pointer;
}
.goTop:hover {
background-color: rgba(33, 81, 129, 1);
transition: 0.3s ease-in-out;
}
.goTopAfter {
transition: 0.3s ease-in-out;
bottom: 100px;
}