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

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

    I modified the code of @TimWolla to add more options and a some movement functions. Also, added support to crossbrowser with document.body.scrollTop and document.documentElement.scrollTop

    // scroll to top
    scrollTo(0, 1000);
    
    // Element to move, time in ms to animate
    function scrollTo(element, duration) {
        var e = document.documentElement;
        if(e.scrollTop===0){
            var t = e.scrollTop;
            ++e.scrollTop;
            e = t+1===e.scrollTop--?e:document.body;
        }
        scrollToC(e, e.scrollTop, element, duration);
    }
    
    // Element to move, element or px from, element or px to, time in ms to animate
    function scrollToC(element, from, to, duration) {
        if (duration <= 0) return;
        if(typeof from === "object")from=from.offsetTop;
        if(typeof to === "object")to=to.offsetTop;
    
        scrollToX(element, from, to, 0, 1/duration, 20, easeOutCuaic);
    }
    
    function scrollToX(element, xFrom, xTo, t01, speed, step, motion) {
        if (t01 < 0 || t01 > 1 || speed<= 0) {
            element.scrollTop = xTo;
            return;
        }
        element.scrollTop = xFrom - (xFrom - xTo) * motion(t01);
        t01 += speed * step;
    
        setTimeout(function() {
            scrollToX(element, xFrom, xTo, t01, speed, step, motion);
        }, step);
    }
    function easeOutCuaic(t){
        t--;
        return t*t*t+1;
    }
    

    http://jsfiddle.net/forestrf/tPQSv/

    Minified version: http://jsfiddle.net/forestrf/tPQSv/139/

    // c = element to scroll to or top position in pixels
    // e = duration of the scroll in ms, time scrolling
    // d = (optative) ease function. Default easeOutCuaic
    function scrollTo(c,e,d){d||(d=easeOutCuaic);var a=document.documentElement;if(0===a.scrollTop){var b=a.scrollTop;++a.scrollTop;a=b+1===a.scrollTop--?a:document.body}b=a.scrollTop;0>=e||("object"===typeof b&&(b=b.offsetTop),"object"===typeof c&&(c=c.offsetTop),function(a,b,c,f,d,e,h){function g(){0>f||1=d?a.scrollTop=c:(a.scrollTop=b-(b-c)*h(f),f+=d*e,setTimeout(g,e))}g()}(a,b,c,0,1/e,20,d))};
    function easeOutCuaic(t){
        t--;
        return t*t*t+1;
    }
    

提交回复
热议问题