繁体   English   中英

如何仅使用Javascript降低默认平滑滚动速度?

[英]How do I slow down the default speed of smooth scroll using only Javascript?

我的目标是按Enter键,并使网站滚动到底部。 我已将滚动行为设置为平滑,并且一切正常进行,但默认情况下平滑滚动的速度太快了。 如何减慢速度? 下面是我的代码。 请不要使用jQuery。 谢谢!

 document.body.onkeyup = function(e){
     if(e.keyCode == 13){
          window.scrollBy(0, window.innerHeight * 8);
     }
 };

您无法更改默认滚动速度。

您可以做的就是创建自己的滚动功能(不使用jQuery)!

 function scrollBy(element, value, duration, easingFunc) { var startTime; var startPos = element.scrollTop; var clientHeight = element.clientHeight; var maxScroll = element.scrollHeight - clientHeight; var scrollIntendedDestination = startPos + value; // low and high bounds for possible scroll destinations var scrollEndValue = Math.min(Math.max(scrollIntendedDestination, 0), maxScroll) // create recursive function to call every frame var scroll = function(timestamp) { startTime = startTime || timestamp; var elapsed = timestamp - startTime; element.scrollTop = startPos + (scrollEndValue - startPos) * easingFunc(elapsed / duration); elapsed <= duration && window.requestAnimationFrame(scroll); }; // call recursive function if (startPos != scrollEndValue) window.requestAnimationFrame(scroll); } var containerEl = document.getElementById("scroll-container"); var scrollingDistance = window.innerHeight * 3; var scrollingTime = 1000; var easeInOutCubic = function(t) { return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1; } scrollBy(containerEl , scrollingDistance , scrollingTime , easeInOutCubic ) 
 html ,body, #scroll-container {height: 100vh; margin:0;} #scroll-container {overflow-y: scroll;position:relative; } section {height: 100%; display:block; position:relative; border-top: 1px solid black;} 
 <div id="scroll-container"> <section id="page1"> page1 </section> <section id="page2"> page2 </section> <section id="page3"> page3 </section> <section id="page4"> page4 </section> </div> 

这样,您可以指定滚动所需的时间。

在示例中,我使用1000ms,但是您可以将其设置为所需的任何值,或者根据滚动量进行设置

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM