【发布时间】: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