Cross browser JavaScript (not jQuery…) scroll to top animation

后端 未结 20 1177
抹茶落季
抹茶落季 2020-11-22 11:01

I\'m looking for a simple, cross-browser \"scroll to top\" animation I can apply to a link. I don\'t want to require a JS library such as jQuery/Moo, etc.

//         


        
20条回答
  •  感动是毒
    2020-11-22 11:40

    Adapted from this answer:

    function scroll(y, duration) {
    
        var initialY = document.documentElement.scrollTop || document.body.scrollTop;
        var baseY = (initialY + y) * 0.5;
        var difference = initialY - baseY;
        var startTime = performance.now();
    
        function step() {
            var normalizedTime = (performance.now() - startTime) / duration;
            if (normalizedTime > 1) normalizedTime = 1;
    
            window.scrollTo(0, baseY + difference * Math.cos(normalizedTime * Math.PI));
            if (normalizedTime < 1) window.requestAnimationFrame(step);
        }
        window.requestAnimationFrame(step);
    }
    

    This should allow you to smoothly scroll (cosine function) from anywhere to the specified "y".

提交回复
热议问题