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

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

    I have choose @akai version of @timwolla answer and added stopAnimation function in return, so before starting new animation, the old one can be stopped.

    if ( this.stopAnimation )
        this.stopAnimation()
    
        this.stopAnimation = scrollTo( el, scrollDestination, 300 )
    
    
    // definitions
    
    function scrollTo(element, to, duration) {
        var start = element.scrollTop,
            change = to - start,
            increment = 20,
            timeOut;
    
        var animateScroll = function(elapsedTime) {        
            elapsedTime += increment;
            var position = easeInOut(elapsedTime, start, change, duration);                        
            element.scrollTop = position; 
            if (elapsedTime < duration) {
                timeOut = setTimeout(function() {
                    animateScroll(elapsedTime);
                }, increment);
            }
        };
    
        animateScroll(0);
    
        return stopAnimation
    
        function stopAnimation() {
            clearTimeout( timeOut )
        }
    }
    
    function easeInOut(currentTime, start, change, duration) {
        currentTime /= duration / 2;
        if (currentTime < 1) {
            return change / 2 * currentTime * currentTime + start;
        }
        currentTime -= 1;
        return -change / 2 * (currentTime * (currentTime - 2) - 1) + start;
    }
    

提交回复
热议问题