当前位置:网站首页>Long list optimized virtual scrolling

Long list optimized virtual scrolling

2022-07-05 14:36:00 Forgive me for not being free and easy enough

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
      ul.container {
    
        position: relative;
        width: 500px;
        max-height: 500px;
        /*  Limit the size of the container display area  */
        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); //  Generate 1000 pieces of data 
    const $list = document.querySelector(".container")
    const size = 20 //  Visual area 10 strip , But you need to scroll   Take the number of pieces each time 20
    createItem(0) //  The default from the 0 Start (i)
    $list.setAttribute("style", `height: ${
      50 * dataList.length}px;`); //  Set container height 
    function handleScroll(e) {
     //  Calculations should show those 
      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) {
     //  Events triggered by scrolling 
      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>
原网站

版权声明
本文为[Forgive me for not being free and easy enough]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051432395612.html