HTML:
<div class="scrollTop" ref="chatScroll"></div>
// class 要设置 overflow-y: auto;
// 设置ref 用来操作DOM属性
js:
//滚动到底
chatScrollTop() {
setTimeout(() => {
//滚动条长度
var currentDistance = this.$refs.chatScroll.scrollHeight - this.$refs.chatScroll.clientHeight;
//当前滚动条距离顶部的距离
var currentScroll_y = this.$refs.chatScroll.scrollTop;
if (currentDistance > 0 && currentDistance > currentScroll_y) {
currentScroll_y = Math.ceil((currentDistance - currentScroll_y) / 10) + currentScroll_y;
currentScroll_y = currentScroll_y > currentDistance ? currentDistance : currentScroll_y;
//微信和qq浏览器不支持 scrollTo?
//this.$refs.chatScroll.scrollTo(0,currentScroll_y);
this.$refs.chatScroll.scrollTop = currentScroll_y;
this.chatScrollTop();
}
}, 13);
},
在需要的地方直接调用chatScrollTop()这个方法即可