1、使用el-scrollbar实现定位滚动(elementui组件库)
如何滚动:参考链接
比如说指定某条对话内容滚动到可视区域的中间
html结构:
<div class="chat-list" id="chat-list"><el-scrollbar ref="scroll" style="height: 100%;"><div v-if="chatListAll.length === 0 && !callEnd" style="color: rgba(0, 0, 0, 0.4); text-align: center;">暂无对话</div><chat-itemv-for="(chat, index) in chatListAll":key="index":chat="chat":searchKey="searchKey"ref="chat":class="chat.isActive ? 'active' : ''"/><div v-if="callEnd" style="color: rgba(0, 0, 0, 0.4); text-align: center;">本次通话已结束</div></el-scrollbar></div>
js计算滚动的代码:
scrollUncivilized(data) {this.$nextTick(() => {let chatDiv = document.querySelector('#chat-list');console.log(chatDiv.offsetHeight);// const parentHeight = chatDiv.offsetHeight - 48; // 减去上下paddingconst parentHeight = chatDiv.clientHeight; // 直接获取可视区域的高度if (this.chatListAll.length) {const index = this.chatListAll.findIndex(item => item.warning === data);if (index > -1) {const itemOffsetTop = this.$refs.chat[index].$el.offsetTop; // item顶部到父元素顶部的距离const itemOffsetHeight = this.$refs.chat[index].$el.offsetHeight; // 元素本身的高度// if (this.$refs.chat[index].$el.offsetTop > parentHeight) {this.$refs['scroll'].wrap.scrollTop = itemOffsetTop - (parentHeight - itemOffsetHeight) / 2;// }// this.$refs.chat[index].$el.scrollIntoView(true);console.log(this.$refs['scroll'].wrap.scrollTop);}}});},
2、使用ScrollIntoView滚动到可视区域
如果对滚动的位置要求不高,只是滚动到可视区域内,可以使用ScrollIntoView滚动到可视区域的顶部或底部
参考链接
参考识别:scrollTop、offsetTop、offsetHeight、clientHeight等
vue实现聊天框自动滚动参考链接