← 所有笔记

el-scrollbar 获取滚动条高度 并将滚动条保持在低端

使用element-plus 的 el-scrollbar 获取滚动条高度,并调整到最低端,适用于聊天界面的开发

首先我们用ref绑定一个 scrollbar

  <el-scrollbar style="height: 100%;" ref="chatScrollRef" @scroll="scrollTest">

用scroll触发滚动事件,一路滚到最底下,观察三个属性

const scrollTest = ({scrollTop}) => {
  console.log(scrollTop);
  const wrap = chatScrollRef.value?.wrapRef
  if (wrap) {
    console.log("------" + wrap.scrollHeight);
    console.log("++++++" + wrap.clientHeight);
    
  }
}

在这里插入图片描述
得出结论,当 scrollTop + clientHeight = scrollHeight 的时候,滚动条会达到最低端

1. 得到滚动条距离顶端高度

先绑定ref

const wrap = chatScrollRef.value?.wrapRef
console.log(wrap.scrollTop);

2. 将滚动条调整在最低端

先绑定ref

const scrollToBottom = () => {
    const wrap = chatScrollRef.value?.wrapRef
    if (wrap) {
      wrap.scrollTop = wrap.scrollHeight - wrap.clientHeight
    }
  })
✳

谢谢你读到这里。

更新于 2025-05-18

搜索笔记

搜索文章标题、标签和正文。

↑ ↓ 选择 · Enter 阅读Esc 关闭