JavaScript 滚动动画:使用 requestAnimationFrame 实现平滑滚动
可以使用 JavaScript 的 window.requestAnimationFrame() 方法来实现滚动动画效果。具体步骤如下:
-
计算出滚动目标的位置。
-
使用
window.scrollY获取当前滚动位置。 -
计算出滚动距离。
-
利用
window.requestAnimationFrame()方法,每一帧更新滚动位置,直到滚动距离为零。
以下是一个简单的示例代码:
function scrollToAnimated(targetY, duration) {
const startY = window.scrollY;
const distance = targetY - startY;
const startTime = performance.now();
function scrollAnimation(currentTime) {
const elapsedTime = currentTime - startTime;
const scrollProgress = Math.min(elapsedTime / duration, 1);
const scrollDistance = distance * scrollProgress;
window.scrollTo(0, startY + scrollDistance);
if (scrollProgress < 1) {
window.requestAnimationFrame(scrollAnimation);
}
}
window.requestAnimationFrame(scrollAnimation);
}
// 使用示例
scrollToAnimated(1000, 1000); // 在1秒内滚动到页面高度为1000的位置
此代码将在1秒钟内滚动到页面高度为1000的位置,您可以根据需要调整目标位置和持续时间。
原文地址: http://www.cveoy.top/t/topic/mGqM 著作权归作者所有。请勿转载和采集!