You need to enable JavaScript to run this app. 如何实现类似Figma等SVG编辑器的<div>无限滚动效果
优惠活动
大模型
产品
解决方案
定价
更多

如何实现类似Figma等SVG编辑器的<div>无限滚动效果

实现方案

原代码问题分析

原有代码存在几个核心问题:

  • 没有判断滚动方向,无论上下滚动都只会增加元素高度
  • 固定加3px的逻辑和实际滚动位移不匹配,会出现滚动跳变
  • 没有设置高度下限,回滚时无法合理缩减高度
  • 修改高度后没有同步调整滚动位置,会出现内容跳动问题

完整实现代码

首先是基础结构和样式:

<div class="container">
  <div class="child">
    <!-- 你的内容放在这里 -->
  </div>
</div>
.container {
  width: 100%;
  height: 600px; /* 视口高度,可自行调整 */
  overflow: auto;
  border: 1px solid #eee;
}
.child {
  width: 100%;
  min-height: 600px; /* 初始最小高度,和container高度保持一致即可 */
  background: #fff;
}

然后是交互逻辑:

const container = document.querySelector('.container');
const child = document.querySelector('.child');
// 配置参数
const MIN_HEIGHT = 600; // 和child的min-height保持一致
const BUFFER = 50; // 触发高度调整的缓冲区,值越大调整越提前
let lastScrollTop = 0;

container.addEventListener('scroll', () => {
  const currentScrollTop = container.scrollTop;
  const childHeight = child.offsetHeight;
  const containerHeight = container.clientHeight;
  // 判断滚动方向
  const isScrollDown = currentScrollTop > lastScrollTop;

  if (isScrollDown) {
    // 向下滚动,接近底部时增加child高度
    if (currentScrollTop + containerHeight >= childHeight - BUFFER) {
      const addHeight = 200; // 每次增加的高度,可自行调整
      child.style.height = `${childHeight + addHeight}px`;
    }
  } else {
    // 向上滚动,距离顶部有足够空间且高度大于最小值时缩减高度
    if (currentScrollTop < BUFFER && childHeight > MIN_HEIGHT) {
      const reduceHeight = Math.min(200, childHeight - MIN_HEIGHT);
      child.style.height = `${childHeight - reduceHeight}px`;
      // 调整滚动位置,避免内容跳变
      container.scrollTop = currentScrollTop + reduceHeight;
    }
  }

  lastScrollTop = currentScrollTop;
});

关键逻辑说明

  • 缓冲区设置:通过BUFFER参数避免滚动到边界才触发调整,减少滚动卡顿感
  • 高度调整阈值:向下滚动时只有接近底部才增加高度,向上滚动时只有接近顶部且当前高度大于最小值才缩减高度
  • 滚动位置同步:向上滚动缩减高度时,同步调整scrollTop值,避免内容出现突然跳动的问题
  • 高度下限控制:设置MIN_HEIGHT保证元素不会缩减到比初始高度更小,避免滚动条异常消失

内容的提问来源于stack exchange,提问作者illogicalapple

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 08:54:07