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

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

    Yet another approach is using window.scrollBy

    JSFiddle

    function scroll(pxPerFrame, duration) {
            if (!pxPerFrame || !duration) return;
            const end = new Date().getTime() + duration;
            step(); 
    
            function step() {
              window.scrollBy(0, pxPerFrame);
              if (new Date().getTime() < end) {
                window.setTimeout(step, 1000 / 60);
              } else {
                console.log('done scrolling'); 
              }
            }
          }
    body {
      width: 200px;
    }
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    <p>
    <button onclick="scroll(-5, 3000)">
    scroll(-5, 3000)
    </button>
    </p>

    0 讨论(0)
  • 2020-11-22 11:47

    I modified TimWolla's answer to use quadratic in-out easing ( a little smoother :). Here is an example in action: on jsFiddle. Easing functions are available here: Robert Penner's Easing functions

    document.getElementsByTagName('button')[0].onclick = function () {
        scrollTo(document.body, 0, 1250);   
    }
    
    function scrollTo(element, to, duration) {
        var start = element.scrollTop,
            change = to - start,
            increment = 20;
    
        var animateScroll = function(elapsedTime) {        
            elapsedTime += increment;
            var position = easeInOut(elapsedTime, start, change, duration);                        
            element.scrollTop = position; 
            if (elapsedTime < duration) {
                setTimeout(function() {
                    animateScroll(elapsedTime);
                }, increment);
            }
        };
    
        animateScroll(0);
    }
    
    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;
    }
    
    0 讨论(0)
  • 2020-11-22 11:49
    window.scroll({top: 0, left: 0, behavior: 'smooth' });
    

    Got it from an article about Smooth Scrolling.

    If needed, there are some polyfills available.

    0 讨论(0)
  • 2020-11-22 11:49

    Easy.

    var scrollIt = function(time) {
        // time = scroll time in ms
        var start = new Date().getTime(),
            scroll = document.documentElement.scrollTop + document.body.scrollTop,
            timer = setInterval(function() {
                var now = Math.min(time,(new Date().getTime())-start)/time;
                document.documentElement.scrollTop
                    = document.body.scrollTop = (1-time)/start*scroll;
                if( now == 1) clearTimeout(timer);
            },25);
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 11:51

    Use this solution

    animate(document.documentElement, 'scrollTop', 0, 200);
    

    Thanks

    0 讨论(0)
提交回复
热议问题