[英]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.