虚拟列表js代码
时间: 2023-08-08 13:09:36 浏览: 40
以下是一个简单的虚拟列表的 JavaScript 代码示例:
```javascript
const container = document.querySelector(".container");
const itemHeight = 50; // 每个项的高度
const itemCount = 1000; // 总共的项数
const visibleCount = Math.ceil(container.clientHeight / itemHeight); // 可见的项数
function createItem(index) {
const item = document.createElement("div");
item.textContent = `Item ${index}`;
item.style.height = `${itemHeight}px`;
return item;
}
function render(startIndex) {
const fragment = document.createDocumentFragment();
for (let i = startIndex; i < startIndex + visibleCount; i++) {
const item = createItem(i);
fragment.appendChild(item);
}
container.innerHTML = "";
container.appendChild(fragment);
}
let startIndex = 0;
render(startIndex);
container.addEventListener("scroll", () => {
const scrollTop = container.scrollTop;
startIndex = Math.floor(scrollTop / itemHeight);
render(startIndex);
});
```
这个代码使用了一个固定高度的容器,其中包含了一个虚拟列表。当用户滚动容器时,列表中显示的项会根据滚动位置进行动态调整。实际上,只有可视区域内的项才会被创建和渲染,而不是所有的项。这种技术可以提高页面性能并减少资源占用。