有没有办法加快scrollTo的行为速度?
我找不到任何东西,这让我想不到。但如果有人知道的更好......
我在speed
和duration
的黑暗中被刺了,但没有去。
window.scrollTo({
top: 1000,
behavior: "smooth"
});
https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
答案 0 :(得分:5)
使用Promise的有效解决方案:
function scrollDelay(ms) {
return new Promise(res => setTimeout(res, ms));
}
document.getElementById("slow-scroll-demo-button").onclick = async function() {
for (var y = 0; y <= 4200; y += 100) {
window.scrollTo({top: y, behavior: 'smooth'})
await scrollDelay(100)
}
}
介绍滚动延迟的技巧:
创建名为async function
的 scrollDelay()
,它会通过兑现承诺来花费时间
在scrollDelay
循环中调用scrollTo
和for
答案 1 :(得分:2)
纯 javascript 解决方案,请参阅以下示例:
https://jsfiddle.net/rafarolo/zwkesrxh/3/
缩小版:https://jsfiddle.net/rafarolo/8orw7ak3/3/
只需更改 scrollTopTo
功能中的第二个参数即可优化速度控制。
// 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;}
答案 2 :(得分:0)
您可以使用间隔计时器来实现自己的滚动或使用jQuery的动画库,详见: