前言
最近做 AI 对话相关项目时遇到一个需求,AI 回答的内容可能会很长,且是一段一段回复的,这时需要在回答时自动将页面滚动到最底部,以显示最新的内容。
实现方法
这个功能实现起来并不困难,核心就是利用标签的 scrollTop
和 scrollHeight
属性。
思路:每当接收到新内容时,将 scrollHeight
值赋给 scrollTop
即可,如果消息不是流式的,可以使用定时器模拟实现。
scrollTop: 一个元素的内容垂直滚动的像素数。
scrollHeight: 元素的高度。
原生
<template>
<div id="scrollcontent"></div>
</template>
// 收到消息
onmessage() {
let scrollcontent = document.getElementById("scrollcontent");
scrollcontent.scrollTop = myDiv.scrollHeight;
scrollcontent = null
}
vue
<template>
<div ref="scrollcontent"></div>
</template>
// 收到消息
onmessage() {
let scrollcontent = this.$refs.scrollcontent
scrollcontent.scrollTop = scrollcontent.scrollHeight;
scrollcontent = null
}
END