首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将变量从js函数传递到gsap scrollTrigger

将变量从js函数传递到gsap scrollTrigger
EN

Stack Overflow用户
提问于 2020-10-28 12:37:57
回答 1查看 613关注 0票数 1

尝试基于窗口宽度修改gsap scrollTrigger offset_value。不幸的是,当用户“动态”改变窗口大小时,无法用(window).resize(function()解决这一问题。此函数对offset_value变量没有影响。

这就是现在的代码,显然,在我的方法中,有什么是根本错误的:

代码语言:javascript
复制
    gsap.registerPlugin(ScrollTrigger);
    var frame_count  = 37,
    offset_value = 360;
if (window.innerWidth < 980) {
    offset_value = 180;
     }
//This is the part that is not working
jQuery(window).resize(function() {
  if( jQuery(this).width() > 979 ){
    offset_value=360;}
    else {offset_value=180;}
    return offset_value;
});
//END This is the part that is not working

gsap.to(".iis-viewer", {
  backgroundPosition: (-offset_value * frame_count * 2) + "px 50%",
  ease: "steps(" + frame_count + ")", // use a stepped ease for the sprite sheet
  scrollTrigger: {
    trigger: ".iis-scene",
    start: "top top",
    end: "+=" + (frame_count * offset_value),
    pin: true,
    scrub: true
  }
});
EN

回答 1

Stack Overflow用户

发布于 2020-10-28 20:42:41

这类情况正是ScrollTrigger的.matchMedia方法的作用所在。

你可以像这样设置你想要做的事情:

代码语言:javascript
复制
ScrollTrigger.matchMedia({
  // desktop
  "(min-width: 980px)": function() {
    const offset_value = 360;
    gsap.to(".iis-viewer", {
      backgroundPosition: (-offset_value * frame_count * 2) + "px 50%",
      ease: "steps(" + frame_count + ")", // use a stepped ease for the sprite sheet
      scrollTrigger: {
        trigger: ".iis-scene",
        start: "top top",
        end: "+=" + (frame_count * offset_value),
        pin: true,
        scrub: true
      }
    });
  },
  
  // mobile
  "(max-width: 979px)": function() {
    const offset_value = 180;
    gsap.to(".iis-viewer", {
      backgroundPosition: (-offset_value * frame_count * 2) + "px 50%",
      ease: "steps(" + frame_count + ")", // use a stepped ease for the sprite sheet
      scrollTrigger: {
        trigger: ".iis-scene",
        start: "top top",
        end: "+=" + (frame_count * offset_value),
        pin: true,
        scrub: true
      }
    });
  }
});

但是,由于您的用例只是切换了几个值(而不是要求不同的when / ScrollTrigger ),所以只使用函数值可能更有意义,因为当ScrollTrigger刷新时(关于大小调整),函数值会被更新:

代码语言:javascript
复制
let offset_value;

function updateOffsetValue() {
  offset_value = innerWidth > 979 ? 360 : 180;
}

window.addEventListener("resize", updateOffsetValue);
updateOffsetValue();

gsap.to(".iis-viewer", {
  backgroundPosition: () => (-offset_value * frame_count * 2) + "px 50%",
  ease: "steps(" + frame_count + ")", // use a stepped ease for the sprite sheet
  scrollTrigger: {
    trigger: ".iis-scene",
    start: "top top",
    end: () => "+=" + (frame_count * offset_value),
    pin: true,
    scrub: true
  }
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64573016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档