将缓动函数应用于Angular / Typescript自动滚动功能

时间:2017-08-29 09:34:42

标签: javascript angular typescript scrolltop autoscroll

对于我的一个应用程序,我编写了一个自动滚动指令,以便某些页面在单击时滚动到锚点链接,而不是立即跳转到它们(它还提供滚动到顶部的功能)。它的效果很好,除了运动是完全线性的,没有自然感觉的加速/减速。我想对滚动运动应用缓动功能,这样感觉更自然,但我无法弄清楚如何实现它。我认为解决方案将涉及在页面滚动时不断重新计算增量,而不是像我在下面那样仅在开始时重新计算一次,但到目前为止,我的实验并没有取得丰硕成果。

我确定其他人已经为Angular编写了一个优秀的平滑滚动指令,但我有兴趣创建自己的指令: - )

有人有什么想法吗?

   @HostBinding('scrollTop') scrollPos: number; // initialized when scroll command is first received

   private setIncrement(destPosition:number) : number { 
      let mod = (destPosition - this.scrollPos < 0) ? -1 : 1;   
      return mod*50;  
   }

   private scrollTo(position:number) : void { 
      this.inc = this.setIncrement(position);
      this.isScrolling = true;
      this.moveIt(this.scrollPos + this.inc);
   } 

   private moveIt(newPos:number) :void { 

      this.scrollPos = Math.min(newPos,this.bottomOfPage); 
      let diff = this.selectedAnchor.position - this.scrollPos; 
      let inView : boolean;

      // ... code that determines if anchor is in view and sets inView ...

      if ( inView || this.scrollPos >= (this.bottomOfPage)) {   
        // ... code that ends scrolling ...
      } 
      else { 
         this.timer = global.setTimeout(()=>{
            this.moveIt(this.scrollPos + this.inc);
         },1);
      }  
   } 

0 个答案:

没有答案