类似向上滚动加载聊天记录,当我滚动到顶部的时候加载聊条记录,然后滚动条依然停留在最顶部,怎么可以停留在当前的位置
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
html, body {
height: 100vh;
background-color: #e9f5f8;
}
.container {
width: 200px;
height: 500px;
overflow-y: auto;
background-color: #FFF;
}
</style>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<div class="container" @scroll="handleScroll" ref="chatListRef">
<ul>
<li v-for="item in msgs"> {{ item }}</li>
</ul>
</div>
</div>
<script type="module">
function generateNumbers(start, end) {
// 确保 start 和 end 是整数
if (!Number.isInteger(start) || !Number.isInteger(end)) {
throw new Error('Both start and end must be integers.');
}
// 确保 start 小于等于 end
if (start > end) {
throw new Error('Start must be less than or equal to end.');
}
// 创建一个空数组来存储结果
const numbers = [];
// 使用 for 循环生成从 start 到 end 的所有数字
for (let i = start; i <= end; i++) {
numbers.push(i);
}
return numbers;
}
// 示例用法
const result = generateNumbers(1, 200);
import { createApp, ref, nextTick } from 'https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-ms/vue/3.2.31/vue.esm-browser.prod.min.js'
createApp({
setup() {
const msgs = ref(result)
const chatListRef = ref()
// 滚动到底部
const scrollToBottom = async () => {
const chatListElement = chatListRef.value
if (chatListElement) {
chatListElement.scrollTop = chatListElement.scrollHeight
}
}
// 向上滚,当滚到顶部的时候添加新数据
const handleScroll = (ev) => {
const target = event.target
if (target.scrollTop === 0) {
msgs.value.unshift(...generateNumbers(201, 400))
alert('添加完数据后希望停留在当前数据的位置,而不是最顶部')
}
}
nextTick(() => {
scrollToBottom()
})
return {
msgs,
chatListRef,
handleScroll
}
}
}).mount('#app')
</script>
</body>
</html>
你要的是不是这个效果https://codepen.io/sqzr123/pen/vYoNWdd