问题描述
尝试根据窗口宽度修改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
}
});