来实现一个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);

你可能感兴趣的:(原生js)