来实现一个js平滑滚动到顶部的小功能

需要添加类名 top

    // 平滑滚动到顶部
    var scrollTopSmooth = function (position) {
        if (!window.requestAnimationFrame) {
            window.requestAnimationFrame = function (cb) {
                return setTimeout(cb, 10);
            };
        }
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        var step = function () {
            var distance = position - scrollTop;
            scrollTop = scrollTop + distance / 5;
            if (Math.abs(distance) < 1) {
                window.scrollTo(0, position);
            } else {
                window.scrollTo(0, scrollTop);
                requestAnimationFrame(step);
            }
        };
        step();
    }
    $backToTop = document.querySelector('.top')
    $backToTop.addEventListener('click', function () {
        scrollTopSmooth(0);
    }, false);




作者:Vam的金豆之路

主要领域:前端开发

我的微信:maomin9761

微信公众号:前端历劫之路