scrollTo speed/duration setting

2019-06-01 09:40发布

Is there a way to speed up the behavior speed of scrollTo?

I can't find anything on it, which makes me think not. But If anyone knows better...

I had a stab in the dark at speed and duration, but no go.

window.scrollTo({
    top: 1000,
    behavior: "smooth"
});

https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo

2条回答
劳资没心,怎么记你
2楼-- · 2019-06-01 10:25

You could use an interval timer to implement your own scrolling or use jQuery's animation library such as detailed in:

https://stackoverflow.com/a/38572744/9510069

查看更多
混吃等死
3楼-- · 2019-06-01 10:45

Pure javascript solution, see the example below:

https://jsfiddle.net/rafarolo/zwkesrxh/3/

Minified version: https://jsfiddle.net/rafarolo/8orw7ak3/3/

Just change the second parameter from scrollTopTo function to refine your speed control.

// scroll to top (0) in 4 seconds e some milliseconds
scrollTo(0, 4269);

// 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;
}

Minified version:

// 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<f||0>=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;}

Reference:

查看更多
登录 后发表回答