[英]Scroll to bottom of div in Polymer on component ready
I am working on a Polymer component where I have a chat box in which I load messages from my Firebase database. 我正在研究Polymer组件,其中有一个聊天框,可在其中从Firebase数据库加载消息。 I want the
div
containing the messages to be scrolled to the bottom when the component is loaded so the user can see the latest messages. 我希望在加载组件时将包含消息的
div
滚动到底部,以便用户可以查看最新消息。
However, I am unable to scroll to the bottom of a div in my Polymer component in ready()
or attached()
lifecycle methods. 但是,我无法使用
ready()
或attached()
生命周期方法滚动到Polymer组件的div底部。 The only time I see the scrolling occur correctly is when I manually trigger the scroll by tapping on my "submit" button (code below). 我唯一看到滚动正确发生的时间是当我通过点击“提交”按钮(下面的代码)手动触发滚动时。
In my Polymer 2.0 element, I have the following code in my component: 在我的Polymer 2.0元素中,我的组件中包含以下代码:
HTML 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 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
}
I am seeing that the scrolling to bottom behavior happens only when I tap on the submit button to manually trigger _onMessagesChanged
. 我看到只有当我点击“提交”按钮手动触发
_onMessagesChanged
时,才会发生滚动到底部的行为。 However, I am not getting the scrolling behavior on initial load of my component. 但是,在组件的初始加载中我没有得到滚动行为。
Any help would be appreciated. 任何帮助,将不胜感激。
Try debounce()
or simply setTimeout()
to delay the invocation of your _scrollToBottom()
. 尝试
debounce()
或简单地setTimeout()
来延迟_scrollToBottom()
的调用。 https://www.polymer-project.org/2.0/docs/upgrade#common-utility-apis https://www.polymer-project.org/2.0/docs/upgrade#common-utility-apis
You can set up a listener for when the dom-repeat changes, and therefor would never have to update it manually. 您可以为dom-repeat更改设置侦听器,因此永远不必手动更新。 Put this after your properties declaration:
将其放在属性声明之后:
listeners: {'dom-change': '_scrollToBottom'},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.