<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>动态加载列表项</title>
<style>
.container {
width: 302px;
height: 100%;
overflow: hidden;
border: 1px solid #ccc; /* 添加灰色边框 */
position: relative;
}
ul#list {
list-style: none;
padding: 0;
margin: 0;
width: 100%;
border: 1px solid #ccc; /* 添加灰色边框 */
border-top: none; /* 取消上边框,避免重叠 */
border-bottom: none; /* 取消下边框,避免重叠 */
}
li {
width: 100%;
border-bottom: 1px dashed #ccc;
}
li a {
text-decoration: none;
color: black;
display: block;
padding: 8px 0;
}
.hidden {
display: none;
}
#loadMore {
width: 100%; /* 和容器宽度相同 */
height: 50px; /* 指定高度 */
border: 1px solid #ccc; /* 添加灰色边框 */
position: absolute; /* 设置绝对定位 */
left: 0; /* 左侧对齐 */
bottom: 0; /* 位于容器下方 */
margin: auto; /* 居中 */
}
</style>
</head>
<body>
<div class="container">
<ul id="list">
<!-- 列表项将在这里动态插入 -->
</ul>
<button id="loadMore">加载更多</button>
</div>
<script>
// 初始化列表项
const initialItems = 10;
const itemsToShow = 5;
const loadMoreCount = 2;
let itemsLoaded = itemsToShow;
// 创建列表项
function createListItem(index) {
const li = document.createElement("li");
li.className = index >= itemsToShow ? "hidden" : "";
const a = document.createElement("a");
a.href = "#";
a.textContent = `列表项 ${index + 1}`;
li.appendChild(a);
return li;
}
// 加载初始列表项
function loadInitialItems() {
for (let i = 0; i < initialItems; i++) {
document.getElementById("list").appendChild(createListItem(i));
}
}
// 加载更多列表项
function loadMoreItems() {
const listItems = document.querySelectorAll("#list li");
for (
let i = itemsLoaded;
i < itemsLoaded + loadMoreCount && i < initialItems;
i++
) {
if (listItems[i]) {
listItems[i].classList.remove("hidden");
}
}
itemsLoaded += loadMoreCount;
}
// 绑定点击事件到加载更多按钮
document
.getElementById("loadMore")
.addEventListener("click", loadMoreItems);
// 初始加载
loadInitialItems();
</script>
</body>
</html>
效果演示图