虛擬列表

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    .list-container {
      overflow: auto;
      border: 1px solid black;
      height: 500px;
    }
  </style>

  <body>
    <!-- 外部容器用來固定列表容器的高度惰许,同時生成滾動條 -->
    <div class="list-container">
      <!-- 內(nèi)部容器用來裝元素,高度是所有元素高度的和 -->
      <div class="list-container-inner"></div>
    </div>

    <script>
      /** --------- 一些基本變量 -------- */
      const itemHeight = 60;
      const height = 500;

      /** --------- 生成數(shù)據(jù) -------- */
      const getRandomHeight = () => {
        // 返回 [60, 150] 之間的隨機數(shù)
        return Math.floor(Math.random() * (150 - itemHeight + 1) + itemHeight);
      };
      const initData = () => {
        const data = [];
        for (let i = 0; i < 15; i++) {
          data.push({
            content: `內(nèi)容:${i}`,
            height: getRandomHeight(),
            color: i % 2 ? 'red' : 'yellow',
          });
        }
        return data;
      };
      const data = initData();
      console.log('data:', data);
      const cacheHeightMap = {};
      const outerContainer = document.querySelector('.list-container');

      const scrollCallback = () => {
        let contentHeight = 0;
        let paddingTop = 0;
        let upperHeight = 0;
        let startIndex;
        let endIndex;
        const innerContainer = document.querySelector('.list-container-inner');
        const scrollTop = Math.max(outerContainer.scrollTop, 0);

        // 遍歷所有的元素扮休,獲取當(dāng)前元素的高度褐奴、列表總高度片拍、startIndex谬哀、endIndex
        for (let i = 0; i < data.length; i++) {
          // 初始化的時候因為元素還沒有渲染悦屏,無法獲取元素的高度
          // 所以用元素的最小高度itemHeight來進行計算黍析,保證渲染的元素個數(shù)能占滿列表
          const cacheHeight = cacheHeightMap[i];
          const usedHeight =
            cacheHeight === undefined ? itemHeight : cacheHeight;

          contentHeight += usedHeight;

          if (contentHeight >= scrollTop && startIndex === undefined) {
            startIndex = i;
            paddingTop = contentHeight - usedHeight;
          }

          if (contentHeight > scrollTop + height && endIndex === undefined) {
            endIndex = i;
            upperHeight = contentHeight;
          }
        }

        // 應(yīng)對列表所有元素沒有占滿整個容器的情況
        if (endIndex === undefined) {
          endIndex = data.length - 1;
          upperHeight = contentHeight;
        }

        // 未渲染的元素的高度由padding-top和padding-bottom代替卖怜,保證滾動條位置正確
        // 這里如果把設(shè)置pading的操作放在渲染元素之后,部分瀏覽器滾動到最后一個元素時會有問題
        const paddingBottom = contentHeight - upperHeight;

        innerContainer.setAttribute(
          'style',
          `padding-top: ${paddingTop}px; padding-bottom: ${paddingBottom}px`
        );

        // 從data取出要渲染的元素并渲染到容器中
        const viewData = data.slice(startIndex, endIndex + 1);

        innerContainer.innerHTML = '';

        const fragment = document.createDocumentFragment();

        for (let i = 0; i < viewData.length; i++) {
          const item = document.createElement('div');
          const itemData = viewData[i];

          item.innerHTML = itemData.content;
          item.setAttribute(
            'style',
            `height: ${itemData.height}px; background: ${itemData.color}`
          );

          fragment.appendChild(item);
        }

        innerContainer.appendChild(fragment);

        // 存儲已經(jīng)渲染出來的元素的高度阐枣,供后面使用
        const children = innerContainer.children;

        let flag = startIndex;

        for (const child of children) {
          cacheHeightMap[flag] = child.offsetHeight;
          flag++;
        }
      };

      // 首屏渲染
      scrollCallback();
      // 監(jiān)聽外部容器的滾動事件
      outerContainer.addEventListener('scroll', scrollCallback);
    </script>
  </body>
</html>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末马靠,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子蔼两,更是在濱河造成了極大的恐慌甩鳄,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件额划,死亡現(xiàn)場離奇詭異妙啃,居然都是意外死亡,警方通過查閱死者的電腦和手機俊戳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門揖赴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人抑胎,你說我怎么就攤上這事燥滑。” “怎么了圆恤?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵突倍,是天一觀的道長腔稀。 經(jīng)常有香客問我,道長羽历,這世上最難降的妖魔是什么焊虏? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮秕磷,結(jié)果婚禮上诵闭,老公的妹妹穿的比我還像新娘。我一直安慰自己澎嚣,他們只是感情好疏尿,可當(dāng)我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著易桃,像睡著了一般褥琐。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上晤郑,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天敌呈,我揣著相機與錄音,去河邊找鬼造寝。 笑死磕洪,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的诫龙。 我是一名探鬼主播析显,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼签赃!你這毒婦竟也來了谷异?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤锦聊,失蹤者是張志新(化名)和其女友劉穎晰绎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體括丁,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡荞下,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了史飞。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片尖昏。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖构资,靈堂內(nèi)的尸體忽然破棺而出抽诉,到底是詐尸還是另有隱情,我是刑警寧澤吐绵,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布迹淌,位于F島的核電站河绽,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏唉窃。R本人自食惡果不足惜耙饰,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望纹份。 院中可真熱鬧苟跪,春花似錦、人聲如沸蔓涧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽元暴。三九已至篷扩,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間茉盏,已是汗流浹背瞻惋。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留援岩,地道東北人。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓掏导,卻偏偏與公主長得像享怀,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子趟咆,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內(nèi)容