html虚拟滚动,解决dom渲染过多卡顿的问题

html虚拟滚动,解决dom渲染过多卡顿的问题_第1张图片


DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <title>极简虚拟滚动title>
    <style>
      .container {
        width: 300px;
        height: 300px;
        border: 1px solid #ccc;
        overflow: auto;
        position: relative;
      }
      .placeholder {
        height: 50000px; /* 假设总高度为1000个item * 50px */
      }
      .item {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 50px;
        line-height: 50px;
        text-align: center;
        box-sizing: border-box;
        will-change: transform;
      }
      .item:nth-child(odd) {
        background-color: #00ccff;
      }
      .item:nth-child(even) {
        background-color: #ffcc00;
      }
    style>
  head>
  <body>
    <div class="container">
      <div class="placeholder">div>
      <div class="items-container">div>
    div>

    <script>
      const container = document.querySelector(".container");
      const itemsContainer = document.querySelector(".items-container");

      const itemHeight = 50;
      const visibleCount = Math.ceil(container.clientHeight / itemHeight); // 屏幕能显示的数量
      const buffer = 2; // 缓冲行数
      const totalItems = 1000; // 总数据量

      function render() {
        const scrollTop = container.scrollTop;
        const startIndex = Math.max(
          0,
          Math.floor(scrollTop / itemHeight) - buffer
        );
        const endIndex = Math.min(
          totalItems,
          startIndex + visibleCount + buffer * 2
        );

        // 清空当前渲染的内容
        itemsContainer.innerHTML = "";

        for (let i = startIndex; i < endIndex; i++) {
          const item = document.createElement("div");
          item.className = "item";
          item.textContent = `Item ${i}`;
          item.style.transform = `translateY(${i * itemHeight}px)`;
          itemsContainer.appendChild(item);
        }
      }

      // 初始渲染
      render();

      // 监听滚动事件
      container.addEventListener("scroll", () => {
        requestAnimationFrame(render);
      });
    script>
  body>
html>

你可能感兴趣的:(html虚拟滚动,解决dom渲染过多卡顿的问题)