可视区域渲染之DOM增减

回到文章>>

COPYHTML

<div class="container"></div>

COPYCSS

.item { height: 80px; margin-bottom: 5px; border-bottom: 1px solid #cccccc; }

COPYJAVASCRIPT

function createDom(start, count, height) { var container = document.querySelector('.container'); // container.style.transform = `translateY(${height}px)`; var div = document.createDocumentFragment(); if (height) { var p = document.createElement('p'); p.style.height = height + 'px'; div.appendChild(p); } for(var i=start, len=start+count; i<len; i++) { var item = document.createElement('div'); item.className = 'item'; item.innerHTML = i; div.appendChild(item); } // 为了方便处理,我们这里采用了更新container中的全部元素 // 你也可以尝试只增加/删除首位的元素,中间元素不变 container.innerHTML = ''; container.appendChild(div); } var start = 0; // 开始位置 var count = 20; // 每页展示的数据 createDom(start, count); // 滚动处理函数 function handleScroller() { var lastStart = 0; // 上次开始的位置 var item = document.querySelector('.container .item'); var itemStyle = getComputedStyle(item); var itemHeight = item.offsetHeight + parseInt(itemStyle['marginTop']) + parseInt(itemStyle['marginBottom']); return function() { var currentScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop); var fixedScrollTop = currentScrollTop - currentScrollTop % itemHeight; var start = Math.floor( currentScrollTop/itemHeight ); // 可视区域开始渲染的位置 if (lastStart!==start) { lastStart = start; createDom(start, count, fixedScrollTop); } } } window.addEventListener('scroll', handleScroller(), false);
新窗口打开