Ionic - 如何确定滚动是否位于内容的底部

时间:2017-10-19 01:49:47

标签: ionic-framework ionic2

我的应用程序中有一些聊天功能,当输入新邮件时,它会自动滚动到<ion-content>的底部,但是,就像许多聊天应用程序一样,如果你在聊天阅读最新消息之前的内容,我不想滚动。只有当用户位于屏幕的最底部时,我才会在新消息进入后滚动到底部。我还没有解决这个问题。

这是我目前的代码:

scrollToBottom() {

  // If the scrollTop is greater than the height, we are at the bottom,
  // in which case, show scrolling animation
  let dimensions = this.content.getContentDimensions();
  let scrollHeight = dimensions.scrollHeight;
  let scrollTop = dimensions.scrollTop;
  let contentHeight = dimensions.contentHeight;
  let heightAndScrollTop = contentHeight + scrollTop;

  // This is the best I can get, assuming that the screen is in a consistent dimension, which we all know is basically non-existent due to all the different types of screens
  if((scrollHeight - heightAndScrollTop) <= 39 && (scrollHeight - heightAndScrollTop) >= 0) { 
    this.content.scrollToBottom(300);
  }
}

知道我能做些什么来解决这个问题吗?

1 个答案:

答案 0 :(得分:5)

首先,在内容底部创建一个元素:

<ion-content>
    //Your messages go here
    ...
    <div id="check-point"></div>  <-- Notice this element
</ion-content>

第二次,编写一个函数来检测视口(可视区域)中的check-point元素是否完全。您可以在SO中轻松找到功能。这是一个简单的:

   //This function just check if element is fully in vertical viewport or not
   isElementInViewPort(element: HTMLElement,  viewPortHeight: number) {
      let rect = element.getBoundingClientRect(); 
      return rect.top >= 0  && (rect.bottom <= viewPortHeight);
   }

最后,每当您推送新邮件时,请检查check-point是否在视口中。如果是,则表示用户位于页面底部。如果不是,则表示用户不是。