本文介绍了scrollTo速度/持续时间设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法加快scrollTo的行为速度?
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...
我在速度
和持续时间
,但没有去。
window.scrollTo({
top: 1000,
behavior: "smooth"
});
推荐答案
纯 javascript 解决方案,请参阅以下示例:
Pure javascript solution, see the example below:
缩小版:
只需将第二个参数从 scrollTopTo
更改为精炼你的速度控制。
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;
}
缩小版:
// 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;}
参考:
- https://stackoverflow.com/a/23844067/5626568
Reference:
这篇关于scrollTo速度/持续时间设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!