如何为现有scrollTop回到顶部函数设置滚动速度且不修改原有代码
可直接追加的自定义滚动时长实现
无需删除你现有代码的任何一行,将下方代码追加到原有JS代码末尾即可生效
实现逻辑
- 你原有CSS中配置的
scroll-behavior: smooth是浏览器内置的固定速度滚动,无自定义配置入口,我们会通过JS内联样式覆盖该行为,不需要修改原有CSS代码 - 利用JS同名函数的覆盖规则,新定义的
topFunction会直接替换原有实现,你原有代码中的按钮显隐判断、滚动事件绑定、按钮样式都完全不受影响 - 所有可调参数集中在代码顶部,调整滚动速度只需要修改对应数值即可
追加代码
直接粘贴到你现有所有JS代码的最后:
// 覆盖原有CSS的固定速度滚动,避免出现双重滚动动画 document.documentElement.style.scrollBehavior = "auto"; document.body.style.scrollBehavior = "auto"; // 滚动效果配置区,仅需修改此处参数即可调整效果 const scrollToTopConfig = { scrollDuration: 800, // 滚动总时长,单位毫秒:数值越小滚动越快,数值越大滚动越慢 easingMode: "easeInOut" // 滚动动画模式:可选linear(匀速)/ easeInOut(缓动,交互手感更自然) }; // 覆盖原有topFunction,按钮的onclick绑定无需任何修改 function topFunction() { const startPos = document.documentElement.scrollTop || document.body.scrollTop; const startTime = performance.now(); function renderFrame(currentTime) { const progress = Math.min((currentTime - startTime) / scrollToTopConfig.scrollDuration, 1); let targetPos; // 按选定的动画模式计算当前滚动位置 if (scrollToTopConfig.easingMode === "linear") { targetPos = startPos * (1 - progress); } else { let easedProgress; if (progress < 0.5) { easedProgress = 2 * progress * progress; } else { easedProgress = -1 + (4 - 2 * progress) * progress; } targetPos = startPos * (1 - easedProgress); } document.documentElement.scrollTop = targetPos; document.body.scrollTop = targetPos; // 动画未完成则执行下一帧,用户中途手动滚动时不会被强制拉扯回顶部 if (progress < 1) requestAnimationFrame(renderFrame); } requestAnimationFrame(renderFrame); }
效果调整方式
- 调整滚动速度:修改
scrollDuration的数值即可,比如设为300是快速回顶,设为2000是慢速回顶 - 调整动画手感:将
easingMode的值从easeInOut改为linear,即可得到匀速滚动的效果
内容的提问来源于stack exchange,提问作者Maniac Piano
相关产品推荐
相关产品推荐

