以编程方式滚动内容不是立即

时间:2017-09-16 08:19:29

标签: angular typescript rxjs

我一直试图找到一种方法在Angular 4中以自然的方式将页面滚动到底部。有一个初始内容块可能会或可能不会延伸到视口之外,然后内容会动态添加随机间隔。内容应在初始加载时滚动到BOTTOM,然后在添加任何内容后滚动到BOTTOM。

在离子中它很简单,它会在300毫秒左右滚动到底部

 @ViewChild(Content) content: Content;

 this.content.scrollToBottom(300)

内容还提供所有当前尺寸

dimensions = this.content.getContentDimensions()

然后可以通过尺寸参考

访问所有当前尺寸
this.dimensions.scrollTop
this.dimensions.contentHeight
this.dimensions.scrollHeight

还有许多其他文档在这里: https://ionicframework.com/docs/api/components/content/Content/

我找不到任何能在Angular中提供相同类型的辅助功能。

所以我根据各种帖子构建了自己的解决方案。我的解决方案使用ElementRef和rxjs。我觉得应该有更好的方法(这使我无法实现)以获得相同的结果!

我目前的解决方案: 我使用ElementRef和Observable.interval()来创建对元素的引用来调整scrollTop。

在.html中

<div #scrollMe>
    //lots of content here that is dynamically added  
</div>

在.ts

@ViewChild('scrollMe') scrollMe: ElementRef;

scrollBottom() { 
//check if the user has scrollup manually and if they have DON'T scrollBottom
if ( window.pageYOffset + window.outerHeight +
     this.scrollMe.nativeElement.scrollTop >
     this.scrollMe.nativeElement.scrollHeight - 300
   ) 
{//Use interval() as a timed iterator
  let myObservable = Observable.interval(20)
  myObservable.takeWhile((data) =>
    //only run while the scroll position is not equal to the scroll height 
    window.pageYOffset + 
    window.outerHeight + 
    this.scrollMe.nativeElement.scrollTop <
    this.scrollMe.nativeElement.scrollHeight)
       .subscribe((output) => {
           //adjust scrollTop by the output amount
           this.scrollMe.nativeElement.scrollTop = 
           this.scrollMe.nativeElement.scrollTop + output
  })
}

间隔发出连续的数字1,2,3,4 ...... 用于滚动页面,如果只有一个短滚动它将 看起来很流畅,如果有一个大的滚动它开始平滑然后加速,所以用户不必等待。

有更好的选择吗?

0 个答案:

没有答案