长列表优化虚拟滚动

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
      ul.container {
        position: relative;
        width: 500px;
        max-height: 500px;
        /* 限定容器展示区域的大小 */
        margin: 0;
        padding: 0;
        border: 1px solid #000;
        overflow-y: auto;
        list-style-type: none;
      }
  
      ul.container li {
        position: absolute;
        width: 100%;
        height: 50px;
        color: white;
        text-align: center;
        line-height: 50px;
      }
    </style>
</head>
<body>
    <ul class="container"></ul>
    <script>
    const dataList = Array.from({ length: 1000 }).map((item, index) => index); // 生成一千条数据
    const $list = document.querySelector(".container")
    const size = 20 // 可视区域10条,但是需要滚动 每次的条数就取20
    createItem(0) // 默认从0开始(i)
    $list.setAttribute("style", `height: ${50 * dataList.length}px;`); // 设置容器高度
    function handleScroll(e) { // 计算应该展示那些
      const i = Math.floor(e.target.scrollTop / 50);
      createItem(i);
    }

    function createItem(i) {
      $list.innerHTML = dataList.slice(i, i + size).map(
        item =>
          `<li style="top: ${item * 50}px; background: ${createHexColor()};">${item}</li>`)
        .join("");
      }
    $list.onscroll = throttle(handleScroll, 20); 
    function throttle(fn, delay) { // 滚动触发的事件
      let lastTime = 0;
        return function () {
          const nowTime = +new Date();
          if (nowTime - lastTime > delay) {
            fn.apply(this, arguments);
            lastTime = nowTime;
          }
        }
      }
      function createHexColor() {
        const colorStr = "6789abcdef",
        	len = colorStr.length;
        let colorVal = "#";
        for (let i = 0; i < 6; i++) {
          colorVal += colorStr[Math.floor(Math.random() * len)];
        }
        return colorVal
      }
    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值