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

后端 未结 20 1064
抹茶落季
抹茶落季 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:51

    Another cross-browser approach based on above solution

    function doScrollTo(to, duration) {
        var element = document.documentElement;
    
            var start = element.scrollTop,
            change = to - start,
            increment = 20,
            i = 0;
    
        var animateScroll = function(elapsedTime) {
            elapsedTime += increment;
            var position = easeInOut(elapsedTime, start, change, duration);
            if (i === 1 && window.scrollY === start) {
                element = document.body;
                start = element.scrollTop;
            }
            element.scrollTop = position;
            if (!i) i++;
            if (elapsedTime < duration) {
                setTimeout(function() {
                    animateScroll(elapsedTime);
                }, increment);
            }
        };
    
        animateScroll(0);
    }
    

    The trick is to control the actual scroll change, and if it is zero, change the scroll element.

提交回复
热议问题