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

GSAP ScrollTrigger 滚动吸附到非预期位置问题求助

GSAP ScrollTrigger 滚动吸附到非预期位置问题求助

我肯定是把GSAP ScrollTrigger的滚动吸附逻辑搞错了,但死活找不到问题所在——我感觉自己完全是照着文档来写的啊。

我的页面内容包含四个带.sectionContainer类的区块,每个区块的高度刚好等于一个视口高度。我想要实现的效果是:用户滚动结束后,页面自动吸附到最近的、能完整显示一个.sectionContainer的位置,绝对不能停在两个区块的中间地带。

但实际测试的时候,GSAP经常会把页面吸附到两个区块之间的位置,哪怕我觉得自己计算的吸附点是完全正确的。

举个实际计算的例子:总高度3578px,区块高度832px,再加上.contentContainer顶部的50px内边距,通过我写的映射函数sections.map((_, i) => offSet * (i + 1) + i * sectionCoverage)算出来第一个吸附点是0.0139742873113471,第二个区块#secondSectionContainer的吸附点是0.26048071548351,逻辑上我觉得这完全没问题,但代码运行起来却会吸附到第一个区块内部的某个位置,实在搞不懂哪里错了。

有没有大佬能帮我指出问题所在?

代码示例

JavaScript

gsap.registerPlugin(ScrollTrigger);

const totalHeight = document.querySelector('.contentContainer').scrollHeight;
const sectionHeight = document.querySelector('.sectionContainer').offsetHeight
const sectionCoverage = sectionHeight/totalHeight;
const contentContainerGap = 50;
const offSet = contentContainerGap/totalHeight;


let sections = gsap.utils.toArray('.sectionContainer');
let snapPoints = sections.map((_, i) => offSet * (i + 1) + i * sectionCoverage);
console.log('snapPoints: ', snapPoints);

ScrollTrigger.create({
    trigger: ".contentContainer",
    start: "top top",
    end: "bottom bottom",
    snap: {
        snapTo: snapPoints,
        duration: 0.5,
        ease: "power1.inOut"
    },
    markers: true
});

CSS

.contentContainer {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    gap: 50px;
    padding: 50px 0 50px 0;
    align-items: center;
}

.sectionContainer {
    border: 2px solid blue;
    width: 90%;
    height: 100vh;
    padding: 20px;
}

#firstSectionContainer {
  background-color: red;
}

#secondSectionContainer {
  background-color: green;
}

#thirdSectionContainer {
  background-color: yellow;
}

#fourthSectionContainer {
  background-color: purple;
}

HTML

<div id="contentContainer" class="contentContainer">
  <div id="firstSectionContainer" class="sectionContainer">
  </div>
  <div id="secondSectionContainer" class="sectionContainer">
  </div>
  <div id="thirdSectionContainer" class="sectionContainer">
  </div>
  <div id="fourthSectionContainer" class="sectionContainer">
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.7/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.7/dist/ScrollTrigger.min.js"></script>

备注:内容来源于stack exchange,提问作者okost

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 12:03:08