平滑滚动函数 smoothScrollTo
这是一个 JavaScript 函数,可以实现平滑滚动至指定位置。
function smoothScrollTo(targetY, duration) {
const startY = window.pageYOffset;
const distance = targetY - startY;
const startTime = performance.now();
function step(currentTime) {
const elapsedTime = currentTime - startTime;
const progress = Math.min(elapsedTime / duration, 1);
const ease = easingFunction(progress);
window.scrollTo(0, startY + distance * ease);
if (elapsedTime < duration) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
function easingFunction(t) {
return t * t * t;
}
// 使用示例
const button = document.querySelector('#scrollButton');
button.addEventListener('click', () => {
smoothScrollTo(1000, 1000);
});
调用 smoothScrollTo
函数并传入目标位置和持续时间参数,就可以实现平滑滚动效果。
该函数的原理是通过不断计算当前进度,然后根据缓动函数计算出对应的滚动位置,最终调用 window.scrollTo
实现滚动。其中,requestAnimationFrame
方法用于请求下一帧动画,以达到更加平滑的效果。
缓动函数 easingFunction
可以根据需求自行替换,本例中使用的是三次方缓动函数。
说明
currentTime
是 requestAnimationFrame 回调函数内部自动传入的参数,表示当前执行回调函数的时间戳。- 它是一个高精度的时间戳,单位为
毫秒
,可以用来计算动画的进度和时间间隔。 - 在 step 函数中,通过计算
elapsedTime
来获取动画已经进行的时间,然后根据 easingFunction 计算出当前的进度 progress,最后根据进度和缓动函数的返回值,计算出滚动位置并调用 window.scrollTo 方法进行滚动。如果动画的持续时间还未过去,就继续调用 requestAnimationFrame 请求下一帧动画,实现平滑滚动效果。