由于ScrollSmoother可能会对滚动事件进行代理或修改,因此直接使用javascript原生的滚动事件监听可能不可靠,但是ScrollSmoother插件本身也没有提供直接获取滚动方向的方法,所以需要自行编写获取代码。
通常判断滚动方向的方法是通过比较当前滚动位置和上一次的位置,如果当前值大于上一次则是向下滚动,反之则是向上。但ScrollSmoother可能会对原生的滚动行为进行封装,所以使用ScrollSmoother或ScrollTrigger提供的API或方法获取滚动位置来判断滚动方向可以确保准确性。
ScrollSmoother实例有一个方法叫做scrollTop()可以获取当前的滚动位置,通过在onUpdate回调中这个值的变化,可以计算出滚动的方向。
思路整理:
通过 ScrollSmoother 的 scrollTop() 方法获取当前平滑处理后的滚动位置。
记录上一次的滚动位置,通过比较当前和上次的值判断方向。
在 ScrollSmoother 的 onUpdate 回调中实时监听滚动变化。
实现代码:
gsap.registerPlugin(ScrollSmoother);
const smoother = ScrollSmoother.create({
smooth:2,
effects:true,
smoothTouch:0.1,
onUpdate:(self) => {
const currentScrollY = self.scrollTop();
const deltaY = currentScrollY - (self.lastScrollY || 0);
const direction = deltaY > 0 ? "down" : "up";
self.lastScrollY = currentScrollY;
if(direction == 'up'){
alert('向上滚动');
}else if(direction == 'down'){
alert('向下滚动');
}
}
});相当简单!