监听的滚动条需要平稳滑动,所以设置几个值,一个定时器。一个定义的scrollTop,方便后续操作
data(){
scrollTop: 0,
timer: null,
scrollBottom: 0,
timers: null,
// 回到底部的,距离底部的scrolltop
bottomHeight: 0
}
首先像大多数一样。可以在挂载的时候写一个监听scroll,注意:选择的容器一定要是包含滚动条的,笔者之前老想获取的容器高度。根本没得滚动条。哭辽哭辽~~
mounted() {
this.$el.querySelector("#chatList").addEventListener("scroll", this.scrollToTop);
},
就像写括号先把后半截写出来一样,addEventListener也需要移除的吖
destroyed() {
clearInterval(this.timer);
this.$el.querySelector("#chatList").removeEventListener("scroll", this.scrollToTop);
},
接下来就是实现的方法了
// 监听的事件
scrollToTop() {
console.log(this.$el.querySelector("#chatList").scrollTop);
this.scrollTop = this.$el.querySelector("#chatList").scrollTop;
},
// 点击回到顶部的事件
backTop() {
clearInterval(this.timers);
// 重新点击回到顶部。清除之前的定时器
if (this.timer != null) {
clearInterval(this.timer);
}
this.timer = setInterval(() => {
this.scrollToTopTimer();
}, 20);
},
// 平缓滚动的事件
scrollToTopTimer() {
let scrollTop = this.scrollTop;
if (scrollTop > 0) {
scrollTop -= 100;
if (scrollTop <= 0) {
scrollTop = 0;
clearInterval(this.timer);
}
}
this.$el.querySelector("#chatList").scrollTop = scrollTop;
},
回到底部事件,没得平缓的过程,等以后补充
setScrollBottom() {
const container = this.$el.querySelector("#chatList");
container.scrollTop = container.scrollHeight;
},
回到底部的动画过程来了
// 回到底部
setScrollTop() {
clearInterval(this.timer);
if (this.timers != null) {
clearInterval(this.timers);
}
const container = this.$el.querySelector("#chatList");
// 浏览器可视窗口的高
const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
this.bottomHeight = container.scrollHeight - clientHeight;
//超出窗口的值就是底部的scrolTop的值
this.timers = setInterval(() => {
this.scrollToBottomTimers();
}, 20);
},
// 回到底部的定时的函数
scrollToBottomTimers() {
// 回到顶部到半路,点击回到底部的时候
if (this.scrollTop != this.$el.querySelector("#chatList").scrollHeight) {
this.scrollBottom = this.scrollTop;
}
if (this.scrollBottom >= this.bottomHeight) {
clearInterval(this.timers);
} else {
this.scrollBottom += 100;
}
this.$el.querySelector("#chatList").scrollTop = this.scrollBottom;
},