虚拟滚动列表是一种性能优化技术,用于只渲染可视区域内的元素,而不是渲染列表中所有的元素。这在处理大量数据时非常有用,可以显著提高应用的性能和响应速度。以下是使用JavaScript和CSS实现虚拟滚动列表的一个基本示例。
HTML
<div id="virtual-list" class="virtual-list"> <!-- 列表项将被动态插入 --> </div>
CSS
.virtual-list { width: 300px; height: 500px; overflow-y: scroll; border: 1px solid #ccc; } .list-item { height: 50px; padding: 10px; box-sizing: border-box; border-bottom: 1px solid #eee; }
JavaScript
class VirtualList { constructor(options) { this.container = document.querySelector(options.container); this.itemHeight = options.itemHeight; this.totalItems = options.totalItems; this.visibleItems = Math.ceil(this.container.clientHeight / this.itemHeight); this.items = []; } render() { this.container.innerHTML = ''; this.calculateItemsToRender(); this.items.forEach(item => { const element = document.createElement('div'); element.className = 'list-item'; element.textContent = `Item ${item + 1}`; this.container.appendChild(element); }); } calculateItemsToRender() { const start = this.getScrollTopIndex(); const end = start + this.visibleItems; this.items = Array.from({ length: this.visibleItems }, (_, i) => start + i); } getScrollTopIndex() { return Math.floor(this.container.scrollTop / this.itemHeight); } onScroll() { this.calculateItemsToRender(); this.render(); } } // 初始化虚拟滚动列表 const virtualList = new VirtualList({ container: '#virtual-list', itemHeight: 50, totalItems: 10000 }); virtualList.render(); // 监听滚动事件 virtualList.container.addEventListener('scroll', ()