如何加快scrollTo方法的平滑滚动速度?
解决window.scrollTo平滑滚动速度无法自定义的问题
嘿,这个问题我之前也踩过坑!原生的window.scrollTo使用behavior: "smooth"时,根本不支持speed或duration参数——这就是你设置了也没效果的原因。浏览器自带的平滑滚动是由内核控制的,并没有开放这些配置项给开发者。
要自定义滚动速度/时长,我们可以自己实现一个平滑滚动函数,用requestAnimationFrame来精确控制每帧的滚动位置。下面是一个实用的示例:
自定义平滑滚动函数
function smoothScrollTo(targetTop, duration = 500) { const startTop = window.pageYOffset; const distance = targetTop - startTop; let startTime = null; // 核心动画函数 function scrollAnimation(currentTime) { if (startTime === null) startTime = currentTime; // 计算已流逝时间占总时长的比例 const timeElapsed = currentTime - startTime; const progress = Math.min(timeElapsed / duration, 1); // 可选:添加缓动效果,让滚动更自然(这里用ease-in-out) const easedProgress = progress * progress * (3 - 2 * progress); // 计算当前应该滚动到的位置 const currentTop = startTop + (distance * easedProgress); window.scrollTo(0, currentTop); // 动画未结束就继续下一帧 if (timeElapsed < duration) { requestAnimationFrame(scrollAnimation); } } requestAnimationFrame(scrollAnimation); }
使用方法
调用这个函数时,传入目标滚动位置和你想要的时长(数值越小,滚动速度越快):
// 用300ms滚到top:1000的位置,比原生平滑滚动快很多 smoothScrollTo(1000, 300);
补充说明
原生window.scrollTo的配置项只有以下三个:
top:目标垂直滚动位置left:目标水平滚动位置behavior:滚动行为(auto/smooth)
所以你之前尝试的speed和duration参数会被浏览器直接忽略,这就是它们不生效的原因。
内容的提问来源于stack exchange,提问作者GoldenGonaz
相关产品推荐
相关产品推荐

