-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
55 lines (55 loc) · 2.09 KB
/
script.js
File metadata and controls
55 lines (55 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 初始化一个空数组,用于存储大量数据
const data = [];
for (let i = 0; i < 100000; i++) {
data.push(i);
}
// 获取列表容器和幽灵元素(用于模拟数据加载效果)
const list = document.querySelector(".list");
const phantom = document.querySelector(".phantom");
// 以下注释代码为之前的加载方式,后被优化替换
// data.forEach(item => {
// const div = document.createElement("div");
// div.innerText = item;
// list.append(div);
// })
// 定义每个元素的高度为50px
const itemHeight = 50;
// 定义容器的高度为300px
const containerHeight = 300;
// 获取容器元素
const container = document.querySelector(".container");
// 计算所有元素的总高度
const totalHeight = data.length * itemHeight;
// 使用幽灵元素撑开容器,以适应内容的高度
phantom.style.height = totalHeight + "px";
// 计算容器能容纳的最大元素个数
const maxCount = Math.ceil(containerHeight / itemHeight);
/**
* 渲染函数,根据滚动位置动态加载数据
*/
function render() {
// 清空列表内容,准备重新渲染
list.innerHTML = "";
// 获取容器的滚动高度
const scrollTop = container.scrollTop;
// 计算当前滚动位置对应的起始数据索引
const start = Math.floor(scrollTop / itemHeight);
// 计算当前滚动位置对应的结束数据索引
const end = Math.ceil(start + maxCount);
// 从数据数组中截取当前需要显示的数据片段
const temp = data.slice(start, end + 1);
// 计算列表顶部的偏移高度,使其与最近的数据元素对齐
const offsetTop = scrollTop - (scrollTop % itemHeight);
// 遍历数据片段,创建并添加到列表中
temp.forEach((item) => {
const div = document.createElement("div");
div.innerText = item;
list.append(div);
});
// 应用偏移高度,使列表内容与滚动位置对齐
list.style.transform = `translateY(${offsetTop}px)`;
}
// 初始加载
render();
// 监听容器滚动事件,实时调整列表内容
container.addEventListener("scroll", render);