.scrollTo
.scrollTo( target:Number | String | Element, smooth:Boolean, position:String ) ;
滚动到特定位置或元素。
参数
目标对象: 数值 | 字符串 | 元素
目标元素,或者使用一个数值来指定特定的滚动位置(像素)。你可以使用选择器文本或元素本身,例如
"#box1"
smooth:布尔值
如果
true
,平滑滚动效果将根据你配置 ScrollSmoother 的方式应用(例如smooth: 1
将会花费 1 秒钟)。请记住,默认情况下在移动设备上没有平滑滚动效果(比如smoothTouch: 0
),否则它将立即跳转到目标位置。位置:字符串
可以选择性地以空格分隔的形式定义一个位置,比如
"center center"
或者"top 100px"
其中第一个值对应目标元素,第二个值对应视口。所以"top 100px"
表示的是当目标元素顶部位于视口顶部下方 100 像素的位置时。
细节
滚动到特定的目标或位置。你可以指定是否应该立即跳转至该位置,或者在滚动过程中应用平滑效果,甚至可以像这样指定一个位置:"top 100px"
其中第一个值对应目标元素,第二个值对应视口。
示例
当点击按钮时,平滑滚动到 #box1 元素顶部距离视口顶部 100 像素的位置:
let smoother = ScrollSmoother.create({...});
button.addEventListener("click", () => smoother.scrollTo("#box1", true, "top 100px");
或者直接跳转至该元素顶部与视口顶部对齐的位置:
smoother.scrollTo("#box1");
或者指定一个具体的滚动位置(以像素为单位):
smoother.scrollTo(500);
想要不带动画直接跳转到该位置?
指定 false,它将会立即跳转。
smoother.scrollTo(500, false);
想要自定义滚动到该位置的动画?
使用offset()方法来找到正确的位置,并将其传递给 GSAP 动画,例如:
gsap.to(smoother, {
// don't let it go beyond the maximum scrollable area
scrollTop: Math.min(
ScrollTrigger.maxScroll(window),
smoother.offset("#box1", "top 100px")
),
duration: 1,
});
当你通过这种方式设置滚动位置时,即使paused()设置为true
.