Javascript缓动(平滑)回到顶部效果

提供时间精确的,流畅的页面缓动回到顶部效果(Demo)。

/**
 * Scroll to top.
 * @param    {number}    duration    Duration of the animation
 */
function scrollToTop(duration = 750) {
    // More easeing-function: https://github.com/cferdinandi/smooth-scroll
    let easeingFunction = t => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
    let originScrollY = pageYOffset;
    let originScrollX = pageXOffset; // Keep abscissa
    let originTime = Date.now();
    let passedTime = 0;
    let _scrollToTop = () => {
        if (passedTime < duration) {
            passedTime = Date.now() - originTime;
            requestAnimationFrame(_scrollToTop);
            scrollTo(originScrollX, originScrollY * (1 - easeingFunction(passedTime / duration)));
        }
    };
    _scrollToTop();
}
    原文作者:kkocdko
    原文地址: https://segmentfault.com/a/1190000018622138
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞