Javascript 平滑滚动中的计时功能
我有一个平滑的滚动在香草js为我的单页网站,我试图实现没有jquery,我想添加一个计时功能,如立方贝塞尔。有没有办法在javascript中实现这一点?代码如下:Javascript 平滑滚动中的计时功能,javascript,html,css,Javascript,Html,Css,我有一个平滑的滚动在香草js为我的单页网站,我试图实现没有jquery,我想添加一个计时功能,如立方贝塞尔。有没有办法在javascript中实现这一点?代码如下: { 'use strict'; let currentY = 0; let destination = 0; let speed = 40; let scroller = null; function smoothScroll(id) { destination
{
'use strict';
let currentY = 0;
let destination = 0;
let speed = 40;
let scroller = null;
function smoothScroll(id) {
destination = document.getElementById(id).offsetTop;
//if the user scrolls down
if (window.pageYOffset < destination) {
scroller = setTimeout(function () {
smoothScroll(id);
}, 1);
currentY = currentY + speed;
if (currentY >= destination) {
clearTimeout(scroller);
}
//if the user scrolls up
} else {
scroller = setTimeout(function () {
smoothScroll(id);
}, 1);
currentY = currentY - speed;
if (currentY <= destination) {
clearTimeout(scroller);
}
}
window.scroll(0, currentY);
}
window.onscroll = function () {
currentY = this.pageYOffset;
};
Array.from(document.querySelectorAll(".scroll")).forEach(e => {
e.addEventListener('click', () => {
smoothScroll(e.href.split('#')[1]);
});
});
}
{
"严格使用",;
设电流y=0;
设目的地=0;
速度=40;
让scroller=null;
功能平滑滚动(id){
destination=document.getElementById(id).offsetTop;
//如果用户向下滚动
if(window.pageYOffset<目的地){
scroller=setTimeout(函数(){
平滑滚动(id);
}, 1);
电流Y=电流Y+速度;
如果(当前Y>=目的地){
clearTimeout(滚动条);
}
//如果用户向上滚动
}否则{
scroller=setTimeout(函数(){
平滑滚动(id);
}, 1);
currentY=currentY-速度;
如果(当前){
e、 addEventListener('单击',()=>{
smoothScroll(e.href.split(“#”)[1]);
});
});
}
下面是一个代码笔,用来观察它的运行:
提前感谢。首先,您应该使用
requestAnimationFrame(fn)
而不是setTimeout(fn,1)
你的动画系统是渐进式的——它会说“我到了吗?如果没有,走近一点;如果是,停下来。”这是可以的,但它给你的关于动画的唯一信息是它是否完成了
放松就像“当接近终点时,放慢速度”,但你不知道何时接近终点
假设我们想从滚动位置100移动到滚动位置200,从时间0开始,到时间500结束。这是时间到位置的映射。如果是时间250,我们应该在位置150-它们都是一半。同样的事情适用于任何其他时间。这被称为tweening,这是制作动画最常见的方式
一旦我们这样做了,我们就可以放松了。放松功能本身非常简单-
如果您愿意,我可以发布代码,但听起来您自己也在尝试解决这个问题,希望这对您有所帮助,祝您好运。谢谢!不发布代码,我会自己检查。因此,我所要做的就是用requestanimationframe替换setTimeout(同时检查它的工作原理)。其余的代码可以吗?不,你必须以不同的方式编写整个动画。
requestAnimationFrame
不会真正改变任何东西,但这是你“应该”做的setTimeout(fn,1)
。