Skip to content

Instantly share code, notes, and snippets.

@barretlee
Created March 24, 2014 16:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barretlee/9744160 to your computer and use it in GitHub Desktop.
Save barretlee/9744160 to your computer and use it in GitHub Desktop.
<title>百万数据前端快速流畅显示</title>
<style type="text/css">
#box {position: relative; height: 300px; width: 200px; border:1px solid #CCC; overflow: auto}
#box div { position: absolute; height: 20px; width: 100%; left: 0; overflow: hidden; font: 16px/20px Courier;}
</style>
<div id="box"></div>
<script type="text/javascript">
var total = 1e5
, len = total
, height = 300
, delta = 20
, num = height / delta
, data = [];
for(var i = 0; i < total; i++){
data.push({content: "item-" + i});
}
var box = document.getElementById("box");
box.onscroll = function(){
var sTop = box.scrollTop||0
, first = parseInt(sTop / delta, 10)
, start = Math.max(first - num, 0)
, end = Math.min(first + num, len - 1)
, i = 0;
for(var s = start; s <= end; s++){
var child = box.children[s];
if(!box.contains(child) && s != len - 1){
insert(s);
}
}
while(child = box.children[i++]){
var index = child.getAttribute("data-index");
if((index > end || index < start) && index != len - 1){
box.removeChild(child);
}
}
};
function insert(i){
var div = document.createElement("div");
div.setAttribute("data-index", i);
div.style.top = delta * i + "px";
div.appendChild(document.createTextNode(data[i].content));
box.appendChild(div);
}
box.onscroll();
insert(len - 1);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment