如何用纯原生JS实现带指定缓动过渡的返回顶部功能?
纯JavaScript实现带easeInOutQuart缓动效果的返回顶部功能
我来帮你把jQuery版本的返回顶部功能转换成原生JS,同时集成你想要的easeInOutQuart缓动效果~先回顾下你原来的jQuery逻辑:
var up = $('#toTop');
$(window).scroll(function() {
$(this).scrollTop() < 300 ? up.fadeOut() : up.fadeIn();
});
$('#toTop').click(function() {
$('html, body').stop().animate({ scrollTop: 0 }, 2000, 'easeInOutQuart');
});
原生JS没有现成的animate方法,但我们可以用requestAnimationFrame配合缓动函数手动实现,同时用CSS过渡模拟fade效果。下面是完整可运行的实现:
1. 先准备HTML按钮(如果还没有的话)
<button id="toTop" style="position: fixed; bottom: 20px; right: 20px; opacity: 0; transition: opacity 0.3s; cursor: pointer; padding: 10px 15px;">返回顶部</button>
2. 原生JS完整代码
(function() { // 获取返回顶部按钮,避免元素不存在时报错 const arrow = document.getElementById('toTop'); if (!arrow) return; // 滚动监听:控制按钮显示/隐藏 window.addEventListener('scroll', function() { // 根据滚动距离切换按钮透明度,配合CSS过渡实现fade效果 arrow.style.opacity = window.scrollY >= 300 ? '1' : '0'; }); // 定义你需要的easeInOutQuart缓动函数 function easeInOutQuart(t, b, c, d) { t /= d / 2; if (t < 1) return c / 2 * t * t * t * t + b; t -= 2; return -c / 2 * (t * t * t * t - 2) + b; } // 实现缓动滚动到顶部的核心函数 function scrollToTop(duration = 2000) { const startScrollY = window.scrollY; const startTime = performance.now(); function animate(currentTime) { // 计算已流逝时间占总时长的比例 const timeElapsed = currentTime - startTime; const progress = Math.min(timeElapsed / duration, 1); // 用缓动函数计算当前应该滚动到的位置 const targetScrollY = easeInOutQuart(progress, startScrollY, -startScrollY, 1); window.scrollTo(0, targetScrollY); // 动画未结束就继续调用下一帧 if (timeElapsed < duration) { requestAnimationFrame(animate); } } requestAnimationFrame(animate); } // 按钮点击事件:触发滚动动画,加锁防止重复触发 arrow.addEventListener('click', function() { if (arrow.classList.contains('is-scrolling')) return; arrow.classList.add('is-scrolling'); scrollToTop(2000); setTimeout(() => arrow.classList.remove('is-scrolling'), 2000); }); })();
代码说明
- 显示/隐藏逻辑:用
window.scrollY获取滚动距离,通过修改opacity配合CSS过渡实现平滑的fade效果,比原生JS手动修改透明度更高效。 - 缓动函数:完全实现了你需要的
easeInOutQuart效果,参数分别对应:时间进度、初始滚动位置、总滚动变化量、时长比例。 - 滚动动画:用
requestAnimationFrame保证动画的流畅性,加入了简单的状态锁避免重复点击触发多次动画。 - 兼容性:
requestAnimationFrame在现代浏览器都支持,若需兼容老浏览器,可自行添加对应的polyfill。
内容的提问来源于stack exchange,提问作者Joe278
相关产品推荐
相关产品推荐

