在组件准备就绪时滚动到 Polymer 中 div 的底部

Scroll to bottom of div in Polymer on component ready

我正在开发一个 Polymer 组件,其中有一个聊天框,我可以在其中加载来自 Firebase 数据库的消息。我希望包含消息的 div 在加载组件时滚动到底部,以便用户可以看到最新的消息。

但是,在 ready()attached() 生命周期方法中,我无法滚动到 Polymer 组件中 div 的底部。我看到滚动正确发生的唯一一次是当我通过点击我的 "submit" 按钮(下面的代码)手动触发滚动时。

在我的 Polymer 2.0 元素中,我的组件中有以下代码:

HTML

  <!-- CONTAINER TO DISPLAY MESSAGES -->
  <div id="messages_container">
    <template is="dom-repeat" items="{{messages}}" as="message">
          [[message.name]]: [[message.text]]
    </template>
  </div>

  <!-- MESSAGE INPUT -->
  <textarea
    placeholder="Type your message here"
    on-input="_onMessageInput">
  </textarea>
  <paper-button raised id="submit"
    on-tap="_submitMessage">
    Send
  </paper-button>

JS

ready(){
  super.ready();
  this._scrollToBottom(); //calling from ready or attached does not scroll the div to the bottom  

  //I have also tried Polymer.RenderStatus.afterNextRender(this, () => { this._scrollToBottom(); }); but that does not cause scrolling to occur consistently
}

/**
 * Observer triggered when messages are written to Firebase database
 */
_onMessagesChanged(){ 
  this._scrollToBottom();
}

_scrollToBottom(){
  this.$.messages_container.scrollTop = 
  this.$.messages_container.scrollHeight;
}

_submitMessage(){
  // store message in Firebase database code not shown
  // this triggers onMessagesChanged(), which then correctly scrolls the div to the bottom
}

我发现滚动到底部的行为仅在我点击提交按钮手动触发时才会发生 _onMessagesChanged。但是,我在组件的初始加载时没有获得滚动行为。

如有任何帮助,我们将不胜感激。

尝试 debounce()setTimeout() 来延迟 _scrollToBottom() 的调用。 https://www.polymer-project.org/2.0/docs/upgrade#common-utility-apis

您可以为 dom-repeat 更改时设置一个侦听器,因此永远不必手动更新它。将其放在您的属性声明之后:

listeners: {'dom-change': '_scrollToBottom'},