【问题标题】:Scroll to bottom of div in Polymer on component ready在组件准备好时滚动到 Polymer 中 div 的底部
【发布时间】:2017-07-17 02:05:32
【问题描述】:

我正在开发一个 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 时才会发生滚动到底部的行为。但是,我在组件初始加载时没有得到滚动行为。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript scroll polymer scrolltop polymer-2.x


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2012-07-13
        • 2010-09-21
        • 1970-01-01
        • 2014-12-12
        • 1970-01-01
        • 2017-03-02
        相关资源
        最近更新 更多