虚拟列表学习篇

114 阅读1分钟

#一、 index.html文件当中

<!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>虚拟列表</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <div id="virtual-scroller"></div>
    <script src="./VirtualScroller.js"></script>
    <script src="./index.js"></script>
</body>

</html>

二、 index.js当中

function fetchData(pageSize) {
    for (let i = 0; i < pageSize; i++) {
      const dataItem = dummyText.substring(0, Math.round(20 + Math.random() * dummyText.length) * 0.3);
      const length = data.push(dataItem);
      renderItem(dataItem, length - 1);
    }
  }
  
  const virtualScroller = new VirtualScroller({
    element: '#virtual-scroller',
    height: '90vh',
    rowHeight: 40, // px
    pageSize: 10,
    buffer: 10,
    renderItem: function (dataItem) {
      const div = document.createElement('div');
      div.classList.add('row-content');
      div.textContent = dataItem;
      return div;
    },
    loadMore: function (pageSize) {
      const data = [];
      for (let i = 0; i < pageSize; i++) {
        const dataItem = `I'm number ${this.data.length + i}`;
        data.push(dataItem);
      }
      return data;
    }
  });

三、VirtualScroller.js文件当中

function fetchData(pageSize) {
    for (let i = 0; i < pageSize; i++) {
      const dataItem = dummyText.substring(0, Math.round(20 + Math.random() * dummyText.length) * 0.3);
      const length = data.push(dataItem);
      renderItem(dataItem, length - 1);
    }
  }
  
  const virtualScroller = new VirtualScroller({
    element: '#virtual-scroller',
    height: '90vh',
    rowHeight: 40, // px
    pageSize: 10,
    buffer: 10,
    renderItem: function (dataItem) {
      const div = document.createElement('div');
      div.classList.add('row-content');
      div.textContent = dataItem;
      return div;
    },
    loadMore: function (pageSize) {
      const data = [];
      for (let i = 0; i < pageSize; i++) {
        const dataItem = `I'm number ${this.data.length + i}`;
        data.push(dataItem);
      }
      return data;
    }
  });

四、style.css文件

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  
  #virtual-scroller {
    background-color: #f0f2f7;
    overflow: auto;
  }
  
  .row-content {
    height: 100%;
    display: flex; 
    align-items: center;
    justify-content: center;
    font-size: 36px;
    border-bottom: 1px solid #c4c4c4;
  }