虚拟滚动列表


在这里插入图片描述

定高虚拟列表

滚动条位置

  • 容器本身被一个计算好的所有项的列表高度撑开,这样负责展示列表的容器就不用再适配滚动条位置,只负责展示列表内容

三个容器

总容器

  • 负责列表宽高以及给另外两个容器定位

撑开内容容器

  • 提前计算好的列表高度,用于适配滚动条,绝对定位

列表容器

  • 根据撑开的内容容器决定定位,展示列表项,通过 top 或 transform:translate3d(0,npx,0) 进行位置定位,定位的起始点和撑开内容容器一致

计算能放置条数

  • 通过列表高度和最小项的高度,计算能放置多少项

缓存与展示

  • 分三屏进行缓存展示,应对快速滑动情况,即将三屏要展示的列表项放进数组里根据滚动位置进行刷新
    • 上屏:当前展示索引-放置条数<0?0:上屏索引(当前展示索引-放置条数),然后从数组中根据上屏索引切出上屏的内容
    • 中屏:要展示的内容,根据scrollTop和每一项位置进行查找(此处用了二分查找),得出当前展示的索引,然后从数组中根据当前展示的索引切出中屏的内容
    • 下屏:当前展示的索引+放置条数>数组总条数-1?数组总条数:下屏索引(当前展示的索引+放置条数)
  • 设置一个缓存区间:如:[上屏索引+放置条数/2的位置,当前展示展示索引+放置条数/2的位置),在这个区间时,就只让列表跟随背景滑动,不计算上中下屏展示的内容以及对展示容器进行定位

防抖优化

  • 对滑动事件进行防抖:window.requestAnimation进行防抖

分屏后定位

  • 根据上屏索引对应的项进行定位,能保证中屏的第一项在页面第一个起始位置
    • 根据滚动条展示知道,已经根据所有项的高度,进行了背景高度的填充,所以根据scrollTop得出的索引对应的项位置,就是项该在背景容器中的位置
    • 又因为展示有上中下三屏,虽然是上中下三屏,但整个内容都是在一个div中,所以需要根据中屏当前展示索引(scrollTop得出的),换算出上屏索引,再位移到上屏索引的位置
    • 若根据中屏当前展示索引(scrollTop得出的)给div定位,则内容在滑动后,展示的内容是上屏的内容
    • 若无中上屏的缓存展示逻辑和缓存区间,只有一屏,那么会在滑动到下一项时刷新定位,虽然滑动效果一致,但会造成闪屏的现象

内容刷新以及位置重新定位

  • 滑动刷新时机:不考虑缓存等,是滑到当前正在展示的第一条项高度结束,下一条项在屏幕初始位置时,才会进行定位刷新
  • 位置重新定位:刷新根据计算原理知道,下一条项依旧是在屏幕初始位置,所以在显示上虽然展示列表内容的容器重新进行了定位,但下一条项依旧是在屏幕初始位置,所以看起来页面展示内容位置和之前滚动的位置一致

解决快速拖动滚动条白屏问题

  • 增加占位图(loading…)
  • 模拟滚动条(因为原生滚动时和 js 执行是互斥的),根据 mouseover 等判断滚动方向,然后通过 scrollTop 自定义设置滚动速度

效果图:
初始加载中屏和下屏列表项:
在这里插入图片描述
滑动加载上屏列表项:
在这里插入图片描述
滑倒列表中间等过程时,上中下屏都加载:
在这里插入图片描述
刷新内容,重新定位时:
在这里插入图片描述

刷新前:虽然定位的位置和内容变了,但是展示的内容是不变的,所以刷新能和上次滑动状态视觉效果一致
在这里插入图片描述

滑动到伊洛瓦底省的时候刷新:

在这里插入图片描述
在这里插入图片描述

代码示例:
源码地址

<template>
  <div class="wrapper" ref="wrapper" @scroll="onScroll"> // 容器
    // 列表内容总高度,用来保证滚动条位置始终正确,且不需要额外计算
    <div class="background" :style="{height:`${total_height}px`}"></div> 
    // 列表容器,定位起始位置和上面的 background 容器起始位置一致,所以正常滑动会滚动出屏幕,通过 transform 位移回正确的位置
    <div class="list" ref="container">
      // 列表项 
      <div v-for="item in runList" :class="['line',getClass(item.data.type)]" :key="item" style="backgroundColor:red">
        <div class="item lt">{{item.data.name}}</div>
        <div class="item gt">{{item.data.value}}</div>
        <div v-if="item.data.type == 3" class="img-container">
          <img src="../../assets/default.png" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import city_data from "./city.json";

export default {
  props: {
    cache_screens: { // 缓冲的屏幕数量
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      list: [], // 源数据
      runList: [], // 运行时的列表
      total_height: 0, // 列表总高度
      maxNum: 0,// 一屏幕容纳的最大数量
      distance: 0 // 存储滚动的距离
    }
  }, 
  mounted () {
    this.genData();
    this.init();
    this.getRunData();
  },
  methods: {
    getClass (type) {
      switch (type) {
        case 1: return "one";
        case 2: return "two";
        case 3: return "three";
        default:
          return "";
      }
    },
    init () {
      const containerHeight = parseInt(getComputedStyle(this.$refs.wrapper).height);
      //一屏的最大数量
      this.maxNum = Math.ceil(containerHeight / this.min_height);
      console.log('max',this.maxNum)
      console.log(`maxNum:${this.maxNum}`);
    },
    onScroll (e) {
      if (this.ticking) {
        return;
      }
      this.ticking = true;
      requestAnimationFrame(() => {
        this.ticking = false;
      })
      const distance = e.target.scrollTop;
      this.distance = distance;
      this.getRunData(distance);
    },
    //二分法计算起始索引
    getStartIndex (scrollTop) {
      let start = 0, end = this.list.length - 1;
      while (start < end) {
        const mid = Math.floor((start + end) / 2);
        const { top, height } = this.list[mid];
        if (scrollTop >= top && scrollTop < top + height) {
          start = mid;
          break;
        } else if (scrollTop >= top + height) {
          start = mid + 1;
        } else if (scrollTop < top) {
          end = mid - 1;
        }
      }
      return start;
    },
    getRunData (distance = null) {

      //滚动的总距离
      const scrollTop = distance ? distance : this.$refs.container.scrollTop;

      //在哪个范围内不执行滚动
      if (this.scroll_scale) {
        if (scrollTop > this.scroll_scale[0] && scrollTop < this.scroll_scale[1]) {
          return;
        }
      }
      console.log('gg',this.scroll_scale)
      console.log(this.list)

      //起始索引
      let start_index = this.getStartIndex(scrollTop);
      start_index = start_index < 0 ? 0 : start_index;

      //上屏索引
      let upper_start_index = start_index - this.maxNum * this.cache_screens;
      upper_start_index = upper_start_index < 0 ? 0 : upper_start_index;

      // 调整offset
      this.$refs.container.style.transform = `translate3d(0,${this.list[upper_start_index].top}px,0)`;

      //中间屏幕的元素
      const mid_list = this.list.slice(start_index, start_index + this.maxNum);

      // 上屏
      const upper_list = this.list.slice(upper_start_index, start_index);

      // 下屏元素
      let down_start_index = start_index + this.maxNum;

      down_start_index = down_start_index > this.list.length - 1 ? this.list.length : down_start_index;
      console.log('索引',Math.floor(upper_start_index + this.maxNum / 2))

      this.scroll_scale = [this.list[Math.floor(upper_start_index + this.maxNum / 2)].top, this.list[Math.ceil(start_index + this.maxNum / 2)].top];

      const down_list = this.list.slice(down_start_index, down_start_index + this.maxNum * this.cache_screens);

      this.runList = [...upper_list, ...mid_list, ...down_list];
      

    },
    //生成数据
    genData () {
      function getHeight (type) {
        switch (type) {
          case 1: return 50;
          case 2: return 100;
          case 3: return 150;
          default:
            return "";
        }
      }
      let total_height = 0;
      const list = city_data.map((data, index) => {
        const height = getHeight(data.type);
        const ob = {
          index,
          height,
          top: total_height,
          data
        }
        total_height += height;
        return ob;
      })
      this.total_height = total_height; //  列表总高度
      this.list = list;
      this.min_height = 50; // 最小高度是50
    }
  }
}
</script>
<style lang="scss" scoped>
.wrapper {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 60px;
  overflow-y: scroll;
  .background {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: -1;
  }
  .list {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
  }
}
.line {
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  .item {
    height: 100%;
    line-height: 40px;
    color: #999;
    &.lt {
      margin-left: 10px;
    }
    &.gt {
      margin-right: 10px;
    }
  }
  &.one {
    height: 50px;
  }
  &.two {
    height: 100px;
    .item {
      color: #666;
    }
  }
  &.three {
    height: 150px;
    .item {
      color: #005aa0;
    }
    .img-container {
      display: flex;
      align-items: center;
      img {
        width: 100px;
        height: 100px;
        margin-right: 10px;
      }
    }
  }
}
</style>

不定高虚拟列表

  • 先预设每一项的高度,计算虚拟滚动容器的总高度,高度不能太大,否则真实数据到来后可能会造成白屏
    • 当有图片的场景时,还需要在 onLoad 事件中再次重新计算高度
  • 等需要展示的区域重新渲染 dom 后,重新计算每一项高度,更新缓存数组中之前预估高度的相关数值,使之变成真实高度,其它还没有展示的位置因为还没有真实数据,所以还是预估高度
    • 滚动条的位置并不需要所有位置的真实高度,因为 当前已有的真实高度+剩余预估的高度 其实已经是当前滚动容器的 “真实高度”,后续的过程都是将预估的高度变成真实高度,动态改变每一刻容器的大小,可以理解为每一刻都是当前的真实高度,类似懒加载的思路
  • 每次滑动都将预估高度更新成真实高度,已经更新的可以做个标识避免重新计算,随着滚动的过程,会让缓存数组中的数据越来越真实
import React, { useRef, useState } from 'react';
import { useVirtual } from 'react-virtual';

const VIRTUAL_ITEM_HEIGHT = 50; // 默认高度用于估算项目高度

const VirtualList = ({ items }) => {
  const parentRef = useRef();
  const [heights, setHeights] = useState({});

  const virtualizer = useVirtual({
    size: items.length,
    parentRef,
    estimateSize: React.useCallback((index) => heights[index] || VIRTUAL_ITEM_HEIGHT, [heights]),
    overscan: 5,
  });
  
  // 高度更新函数
  const updateItemHeight = (index, el) => {
    const newHeight = el.getBoundingClientRect().height;
    const oldHeight = heights[index];
    if (newHeight !== oldHeight) {
      setHeights((heights) => ({
        ...heights,
        [index]: newHeight,
      }));
    }
  };

  return (
    <div ref={parentRef} style={{ height: '400px', overflow: 'auto', position: 'relative' }}>
      <div style={{ position: 'relative', height: `${virtualizer.totalSize}px` }}></div>
      {virtualizer.virtualItems.map((virtualItem) => {
        const item = items[virtualItem.index];
        return (
          <div
            key={virtualItem.index}
            ref={(el) => el && updateItemHeight(virtualItem.index, el)} // dom 更新后重新计算高度
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              transform: `translateY(${virtualItem.start}px)`,
            }}
          >
            <img
              src={item.image}
              alt={item.name}
              onLoad={({ target }) => updateItemHeight(virtualItem.index, target.parentElement)} // 图片加载后重新计算高度
            />
            <p>{item.name}</p>
          </div>
        );
      })}
    </div>
  );
};

export default VirtualList;
// vue 方式
updated() {
    this.$nextTick(() => {
        this.updatePositions()
    })
},
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值