Created
March 24, 2014 16:45
-
-
Save barretlee/9744160 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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