簡體   English   中英

在組件就緒時滾動到Polymer的div底部

[英]Scroll to bottom of div in Polymer on component ready

我正在研究Polymer組件,其中有一個聊天框,可在其中從Firebase數據庫加載消息。 我希望在加載組件時將包含消息的div滾動到底部,以便用戶可以查看最新消息。

但是,我無法使用ready()attached()生命周期方法滾動到Polymer組件的div底部。 我唯一看到滾動正確發生的時間是當我通過點擊“提交”按鈕(下面的代碼)手動觸發滾動時。

在我的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'},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM