<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="container" style="overflow-y: scroll; height: 500px; background: slategrey">
<div style="height: 50000px">
<ul class="ull" style="text-decoration: none"></ul>
</div>
</div>
</body>
<script>
// 可视区域高度500px item高度50,最大显示10条数据, 展示1000条数据, 容器高度 50*1000 = 50000px
let totalData = Array(1000)
.fill(1)
.map((item, index) => index);
// 首版数据默认展示16条
let initList = Array(Math.floor(500 / 50) )
.fill(1)
.map((item, index) => index);
let ul = document.querySelector(".ull");
// 初始化首版数据
init(initList);
let container = document.querySelector(".container");
function init(list, offset = 0) {
ul.innerHTML = "" // 这里清空很关键
list.forEach((item) => {
let li = document.createElement("li");
li.style = "height: 50px; text-align: center; border: 1px solid black; box-sizing: border-box;";
li.innerHTML = item + 1;
ul.appendChild(li);
});
ul.style = `transform:translateY(${offset}px)`;
}
container.addEventListener("scroll", function (e) {
let scrollTop = e.target.scrollTop;
let num = Math.floor(scrollTop / 50);
let list = totalData.slice(num, num + Math.floor(500 / 50));
let offset = scrollTop - (scrollTop % 50);
init(list, offset);
});
</script>
</html>
h5虚拟滚动
最新推荐文章于 2023-12-28 17:39:39 发布