虚拟列表是只渲染可视区域及缓冲区节点、用空白占位其余项的技术,用于解决大数据量列表的卡顿、高内存和滚动不流畅问题;通过计算滚动位置下的起始/结束索引截取数据,并用 translateY 偏移整体列表实现视觉对齐。

当列表数据量很大(比如上万条),直接渲染所有 DOM 节点会导致页面卡顿、内存占用高、滚动不流畅。虚拟列表只渲染当前可视区域及其少量缓冲区内的节点,其余节点用空白占位,从而大幅减少 DOM 数量和重排重绘开销。
关键在于计算:当前滚动位置下,哪些数据项在视口内?它们应渲染在什么位置?
假设每条数据高度为 50px,容器高 400px,总数据 10000 条:
const container = document.getElementById('list');
const itemHeight = 50;
const visibleCount = Math.ceil(400 / itemHeight); // 约 8 条
let startIndex = 0;
<p>container.addEventListener('scroll', () => {
const scrollTop = container.scrollTop;
startIndex = Math.floor(scrollTop / itemHeight);
const endIndex = Math.min(startIndex + visibleCount + 2, listData.length); // +2 是缓冲</p><p>// 渲染 slice 后的 items,并设置 wrapper 的 translateY
const fragment = document.createDocumentFragment();
const renderList = listData.slice(startIndex, endIndex);
renderList.forEach((item, i) => {
const el = document.createElement('div');
el.textContent = item;
el.style.height = <code>${itemHeight}px</code>;
fragment.appendChild(el);
});
listWrapper.innerHTML = '';
listWrapper.appendChild(fragment);
listWrapper.style.transform = <code>translateY(${startIndex * itemHeight}px)</code>;
});
真实项目中还需考虑这些细节:
立即学习“Java免费学习笔记(深入)”;
基本上就这些。不复杂但容易忽略缓冲区、transform 定位和高度缓存——做好这三点,万级列表也能丝滑滚动。
以上就是JavaScript中如何实现虚拟列表_滚动性能优化的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号