简体   繁体   English

RXJS如何实现平滑滚动

[英]RXJS how to implement a smooth scroll

I am trying to implement a smooth scroll functionality using RXJS. 我正在尝试使用RXJS实现平滑滚动功能。

The following code scrolls smoothly but not as intended. 下面的代码可以平滑滚动,但不能按预期滚动。 it takes much longer time than the duration to reach the target. 比达到目标所需的时间长得多的时间。

Any idea how to fix it? 知道如何解决吗?

const scrollableEl = document.getElementById('view');
const btn = document.getElementById('testBtn');
btn.addEventListener('click', () => {
  scrollTo(scrollableEl, 1000, 300);
});

function scrollTo(scrollableEl: HTMLElement, point: number, duration: number) {

  timer(0, 20, animationFrame).pipe(
    map((elapsedTime: number) => {
      const delta = point - scrollableEl.offsetTop;
      return {
        top: easeInOutQuad(elapsedTime, scrollableEl.offsetTop, delta, duration),
        elapsedTime
      };
    }),
    tap((target) => {
      console.log('scrollTo: ', target);
      scrollableEl.scrollTop = target.top;
    }),
    // Stop timer
    takeWhile((target: any) => target.elapsedTime < duration)
  ).subscribe();
}

Here is a reproduction: https://stackblitz.com/edit/rxjs-35vjhu 这是复制品: https : //stackblitz.com/edit/rxjs-35vjhu

The timer function doesn't emit elapsed time, its output is a sequence of numbers starting from 0: 0, 1, 2, 3 etc. I think you need to measure elapsed time yourself: timer功能不会发出经过的时间,它的输出是一个从0:0、1、2、3等开始的数字序列。我认为您需要自己测量经过的时间:

const startTime = new Date().getTime();
timer(0, 20, animationFrame).pipe(
  map(() => {
    const elapsedTime = new Date().getTime() - startTime;
    const delta = point - scrollableEl.offsetTop;
    return {
      top: easeInOutQuad(elapsedTime, scrollableEl.offsetTop, delta, duration),
      elapsedTime
    };
  }),
  tap((target) => {
    console.log('scrollTo: ', target);
    scrollableEl.scrollTop = target.top;
  }),
  // Stop timer
  takeWhile((target: any) => target.elapsedTime < duration),
).subscribe();

This is updated example: https://stackblitz.com/edit/rxjs-dr44gy 这是更新的示例: https : //stackblitz.com/edit/rxjs-dr44gy

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

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