点击直接回到顶部,无动画效果

1
2
3
4
backTop() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}

先快后慢,效果较好

1
2
3
4
5
6
7
8
9
10
11
12
// 回到顶部
backTop() {
let scrollToptimer = setInterval(function () {
// console.log("定时循环回到顶部");
var top = document.body.scrollTop || document.documentElement.scrollTop;
var speed = top / 4;
document.documentElement.scrollTop -= speed;
if (top == 0) {
clearInterval(scrollToptimer);
}
}, 30);
},

滚动监听,当距离顶部一定高度时隐藏直达顶部按钮

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 在mounted钩子函数中添加监听事件
mounted(){
window.addEventListener("scroll", this.scrollToTop,true);
}

methods: {
// 显示按钮的显示与隐藏
scrollToTop() {
console.log("进来了");
const that = this;
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
that.scrollTop = scrollTop;
if (that.scrollTop > 60) {
that.btnFlag = true;
} else {
that.btnFlag = false;
}
},
}
destroyed() {
// 离开页面时需销毁滚动监听事件
window.removeEventListener("scroll", this.scrollToTop);
},