可视区域渲染之DOM元素复用

回到文章>>

COPYHTML

<div class="container"> <div class="content"> <div class="item item0"></div> <div class="item item1"></div> <div class="item item2"></div> <div class="item item3"></div> <div class="item item4"></div> <div class="item item5"></div> <div class="item item6"></div> <div class="item item7"></div> <div class="item item8"></div> <div class="item item9"></div> <div class="item item10"></div> <div class="item item11"></div> <div class="item item12"></div> <div class="item item13"></div> <div class="item item14"></div> <div class="item item15"></div> <div class="item item16"></div> <div class="item item17"></div> <div class="item item18"></div> <div class="item item19"></div> </div> </div>

COPYCSS

.container { height: 80vh; position: relative; overflow: auto; } .item { min-height: 80px; border-bottom: 1px solid #cccccc; position: absolute; width: 100%; }

COPYJAVASCRIPT

function updateDom(start, count, itemHeight, height) { document.querySelector('.container .content').style.transform = 'translateY('+height+'px)'; for (var i = start, len=start+count; i < len; i++) { var index = i % count; var cssIndex = (i-start) % len; document.querySelector('.item' + index).innerHTML = i; document.querySelector('.item' + index).style.transform = 'translateY('+itemHeight*cssIndex+'px)'; } } var start = 0; // 开始位置 var count = 20; // 每页展示的数据 var itemHeight = 81; // 每个item的高度 document.querySelector('.container .content').style.height = itemHeight * 10000 + 'px'; updateDom(start, count, itemHeight, 0); // 滚动处理函数 function handleScroller() { var lastStart = 0; // 上次开始的位置 var container = document.querySelector('.container'); return function() { var currentScrollTop = container.scrollTop; var fixedScrollTop = currentScrollTop - currentScrollTop % itemHeight; var start = Math.floor( currentScrollTop/itemHeight ); if (lastStart!==start) { lastStart = start; updateDom(start, count, itemHeight, fixedScrollTop); } } } document.querySelector('.container').addEventListener('scroll', handleScroller(), false);
新窗口打开