You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GSAP ScrollTrigger固定容器后仍同时触发垂直与水平滚动的问题求助

GSAP ScrollTrigger固定容器后仍同时触发垂直与水平滚动的问题求助

我完全懂你遇到的糟心问题——本来想做个垂直滚动触发水平位移的效果,结果页面一边水平动,一边还跟着垂直滚,完全没达到“固定容器”的预期。我帮你捋捋问题出在哪,以及怎么解决:

先看你代码里的几个小bug

  1. HTML里features区块的class写错了:h-dvhflex-shrink-0少了空格,应该改成h-dvh flex-shrink-0,这个拼写错误会导致区块高度样式失效,容器高度不对的话,ScrollTrigger的pin功能根本没法正常工作。
  2. 你的页面html和body大概率没设置overflow:hidden,这就导致页面本身存在垂直滚动的空间,哪怕pin了容器,页面还是能继续垂直滚动。

一步步解决问题

1. 先给全局加基础样式

添加这段CSS,把页面本身的垂直滚动条去掉:

html, body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

2. 修正HTML的class错误

把features区块的class改对,确保所有section高度都匹配视口:

<div id="scroll-container" class="w-full h-dvh overflow-hidden relative">
  <div id="section-wrapper" class="flex h-full">
    <section id="home" class="relative flex flex-col h-dvh flex-shrink-0 min-w-full max-w-full">
      ... some content
    </section>
    <section id="features" class="flex flex-col h-dvh flex-shrink-0 min-w-[50%]">
      ... some content
    </section>
    <section id="facts" class="flex flex-col h-dvh flex-shrink-0 min-w-[100%]">
      ... some content
    </section>
  </div>
</div>

3. 优化ScrollTrigger的配置

调整JS代码,确保pin功能完全生效,彻底杜绝垂直滚动:

gsap.registerPlugin(ScrollTrigger);

const sectionWrapper = document.querySelector("#section-wrapper");
const scrollContainer = document.querySelector("#scroll-container");

// 计算需要水平滚动的总距离
const sectionWidth = sectionWrapper.scrollWidth;
const amountToScroll = sectionWidth - window.innerWidth;

// 强制容器高度匹配视口,避免溢出
gsap.set(scrollContainer, { height: window.innerHeight });

const tween = gsap.to(sectionWrapper, {
  x: -amountToScroll,
  duration: 3,
  ease: "none"
});

ScrollTrigger.create({
  trigger: scrollContainer,
  start: "top top",
  // 设置垂直滚动的触发范围等于水平需要滚动的距离
  end: () => `+=${amountToScroll}`,
  // 直接pin当前trigger元素,简化配置
  pin: true,
  animation: tween,
  scrub: true,
  markers: true,
  // 确保滚动触发期间页面不会有垂直滚动
  onToggle: (self) => {
    document.body.style.overflow = self.isActive ? "hidden" : "auto";
  }
});

关键逻辑说明

  • html, body { overflow: hidden } 直接移除页面本身的垂直滚动条,确保只有ScrollTrigger控制的滚动行为生效。
  • 修正class后,所有section高度严格匹配视口,容器不会出现垂直方向的溢出,pin功能才能正确固定住容器。
  • 调整end值和添加onToggle回调,进一步保障在滚动触发期间,页面不会产生额外的垂直滚动。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 08:14:34