我正在尝试编写包含“聊天”和“内容”两个部分的页面。我希望那个“聊天”将页面自动滚动到底部而没有任何效果。聊天是<ion-list>
有几个<ion-item>
.
<ion-list>
<ion-item> item 1 </ion-item>
<ion-item> item 2 </ion-item>
....
<ion-item> item 20 </ion-item>
<ion-item> item 21 </ion-item> <!-- user should see directly this item on bottom of the page -->
</ion-list>
我使用的是 Javascript,而不是 typescript,而且我不想不使用 jQuery。 谢谢 :) 另外,当我转到“内容”部分并返回“聊天”时,我想再次自动滚动聊天。
最佳答案
这是我的做法:
chatPage.html
<ion-content #content padding class="chatPage">
<ion-list no-lines>
<ion-item *ngFor="let msg of messages" >
<chat-bubble [message]="msg"></chat-bubble>
</ion-item>
</ion-list>
</ion-content>
chatPage.html 中重要的一点是 #content
在 <ion-content>
.我将使用 #content
标识符以获取对 <ion-content>
的引用在我的 chatPage.js 中使用 ViewChild
.
现在是实际的滚动逻辑:
chatPage.js
import {Component, ViewChild} from '@angular/core';
@Component({
templateUrl: 'build/pages/chatPage/chatPage.html',
queries: {
content: new ViewChild('content')
}
})
export class ChatPage {
constructor() {
}
//scrolls to bottom whenever the page has loaded
ionViewDidEnter(){
this.content.scrollToBottom(300);//300ms animation speed
}
}
此外,每当我的 chatPage 需要在列表中显示另一条聊天消息(收到新消息或发送新消息)时,我使用以下代码滚动到新底部:
setTimeout(() => {
this.content.scrollToBottom(300);//300ms animation speed
});
Typescript 更新
当我给出这个答案时,我正在使用 Ionic 2 项目的 JavaScript 版本。随着时间的推移,我切换到 TypeScript,但我忘记更新答案,因此,这里有一个针对 chatPage.js(ts) 的小更新:
chatPage.ts
import {Component, ViewChild} from '@angular/core';
@Component({
templateUrl: 'chatPage.html'
})
export class ChatPage {
@ViewChild('content') content:any;
constructor() { }
//scrolls to bottom whenever the page has loaded
ionViewDidEnter(){
this.content.scrollToBottom(300);//300ms animation speed
}
}
关于javascript - ionic 2 + Angular 2 : auto scroll to bottom of list/page/chat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37415085/