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

如何让GSAP与JS仅在视口宽度>1200px时执行水平滚动?

解决方案:仅在宽屏(>1200px)启用GSAP水平滚动

问题根源

原代码只在页面首次加载时判断一次视口宽度,窗口缩放后不会销毁已创建的ScrollTrigger实例,导致窄屏状态下仍保留水平滚动效果。

实现方案

通过封装初始化/销毁函数、监听窗口resize事件并结合防抖处理,动态启用或禁用滚动效果:

const aboutContainer = document.querySelector(".about__container");
const aboutContent = gsap.utils.toArray(".about__container .about__content");
const aboutMask = document.querySelector(".about__mask");

// 存储ScrollTrigger实例,方便后续统一销毁
let scrollTriggers = [];

// 初始化水平滚动及相关动画
function initHorizontalScroll() {
  // 内容水平滚动
  const contentScroll = gsap.to(aboutContent, {
    xPercent: -100 * (aboutContent.length - 1),
    ease: "none",
    scrollTrigger: {
      trigger: ".about__container",
      pin: true,
      scrub: 1,
      end: "+=3000",
    },
  });
  scrollTriggers.push(contentScroll.scrollTrigger);

  // 遮罩宽度动画
  const maskScroll = gsap.to(aboutMask, {
    width: "100%",
    scrollTrigger: {
      trigger: ".about__section",
      start: "top left",
      scrub: 1,
    },
  });
  scrollTriggers.push(maskScroll.scrollTrigger);

  // 内容入场动画
  const tl = gsap.timeline({
    scrollTrigger: {
      trigger: ".about__container",
      start: "center bottom",
    },
  });
  tl.from(aboutContent, { x: 300, opacity: 0, duration: 1 });
  scrollTriggers.push(tl.scrollTrigger);
}

// 销毁所有ScrollTrigger实例并重置元素状态
function destroyHorizontalScroll() {
  scrollTriggers.forEach(trigger => trigger.kill());
  scrollTriggers = [];
  // 重置元素到初始状态,避免窄屏时位置异常
  gsap.set(aboutContent, { xPercent: 0, x: 0, opacity: 1 });
  gsap.set(aboutMask, { width: "" });
}

// 防抖函数,避免resize频繁触发逻辑
function debounce(func, delay = 200) {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
}

// 处理窗口尺寸变化
function handleResize() {
  const isWideScreen = window.innerWidth > 1200;
  // 宽屏且未初始化时,启动滚动效果;窄屏且已初始化时,销毁效果
  if (isWideScreen && scrollTriggers.length === 0) {
    initHorizontalScroll();
  } else if (!isWideScreen && scrollTriggers.length > 0) {
    destroyHorizontalScroll();
  }
}

// 页面首次加载时执行一次判断
handleResize();

// 监听窗口resize事件
window.addEventListener("resize", debounce(handleResize));

关键细节说明

  • 实例管理:用数组存储所有ScrollTrigger实例,确保销毁时能彻底清理所有相关动画
  • 状态重置:销毁时重置元素的位置、透明度等属性,避免窄屏状态下元素显示异常
  • 防抖优化:防止窗口缩放过程中频繁触发初始化/销毁逻辑,减少性能消耗
  • 动态切换:仅在宽屏/窄屏状态切换时执行对应操作,避免重复执行无效逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 08:32:20