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

问题描述

尝试根据窗口宽度修改gsap scrollTrigger offset_value 。不幸的是,当用户“即时”更改窗口大小时,无法弄清楚如何使用(window).resize(function()实现此目的。此功能 offset_value 变量不起作用。

这是现在的代码,显然我的方法存在根本上的错误

    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
  }
});

解决方法

这类情况正是ScrollTrigger的.matchMedia方法所针对的。

您可以像上面这样设置您要尝试做的事情:

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",scrub: true
      }
    });
  }
});

但是,由于您的用例只是切换了几个值(而不是需要不同的补间/ ScrollTriggers),所以使用功能值可能更有意义,因为在ScrollTrigger刷新时(在调整大小时)功能值会更新:

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%",// use a stepped ease for the sprite sheet
  scrollTrigger: {
    trigger: ".iis-scene",end: () => "+=" + (frame_count * offset_value),scrub: true
  }
});

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...