<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat Demo</title>
<style>
#container {
width: 300px;
/* 盒子宽度 */
height: 200px;
/* 盒子高度 */
overflow: auto;
/* 隐藏滚动条 */
position: relative;
}
.scrollable {
height: 100%;
overflow: auto;
/* 启用垂直滚动 */
transition: transform 0.3s ease;
/* 添加平滑滚动效果 */
}
.list-item {
padding: 10px;
border-bottom: 1px solid #ccc;
/* 列表项底部边框 */
}
</style>
</head>
<body>
<div id="container">
<div id="list" class="scrollable">
<!-- 列表项将被动态添加到这里 -->
</div>
</div>
<button id="addItem">添加列表项</button>
<script>
const container = document.getElementById('container')
const list = document.getElementById('list');
const addItemButton = document.getElementById('addItem');
let itemCount = 0;
addItemButton.addEventListener('click', () => {
itemCount++;
const newItem = document.createElement('div');
newItem.className = 'list-item';
newItem.textContent = `列表项 ${itemCount}`;
// 将新项添加到列表的顶部
list.appendChild(newItem);
const ListChind = list.children[list.children.length - 1]
list.style.minHeight = ListChind.offsetTop + 200 + 'px'
setTimeout(() => {
container.scrollTop = list.scrollHeight;
}, 100); // 增加延时以明确效果
// 自动滚动以仅显示最新添加的项
});
</script>
</body>
</html>